❤️ The design mode is finished, quite complete! Tencent and Ali's offer has been taken! ❤️

Java Web Development It was included in two columns at the same time
45 articles 20 subscriptions
61 articles 41 subscriptions

The design mode is finished, quite complete! Tencent and Ali's offer has been taken!

The golden nine and silver ten have come. It's very close. The best opportunity for the big factory has come! If you are looking for a job, you must seize this opportunity!

Many interview materials have been sorted out:

1,❤️ liver failure! Sorted out the spring interview [including answers] for a week and hanged the Java interviewer [suggestions collection]! ❤️

2,❤️ When the liver is over, master the data structure and algorithm one day, interview questions, hang the interviewer, and suggest collecting ❤️

3,❤️ Is the collection simple? Are you kidding? Liver for a week, is the essence, all words to explain! Interview is no longer afraid of questions!!! ❤️

4,After that, I summarized the knowledge points of springboot and cache, and quickly mastered them

5,MySQL interview encyclopedia, after reading it, you can hang and beat the interviewer!!!

6,Junior brothers and sisters majoring in computer, don't be confused. I'll sort out a complete collection of CS learning routes! Help you surpass most of your classmates!

7,❤️ Junior college background, get Ali offer, Xiao Meng calls 666【 [hard core interview] ❤️

A small partner in front is well prepared and has already got offers from Ali and Tencent. Through talking with him, I found that the probability of design pattern quilt is basically 100%.

 

  Last time I voted, there were many students in the big factory. Welcome to give me face-to-face experience and quality. I can pay for the value and help you, me and him!

No more nonsense, just do it!

catalogue

Q1: how many design patterns are there?

Q2: what are the principles of design pattern?

Q3: classification of design patterns. Which design patterns do you know?

Q4: simple mode

Q5: speaking, speaking, and law mode

Q6: what design patterns are used in the spring framework?

Q7: do you understand the abstract ⼯ pattern?

Q8: what are the characteristics of singleton mode?

Q9: what are the implementations of singleton mode?

Q10: talk about agent mode

Q11: talk about decorator mode

Q12: what is the difference between decorator mode and dynamic agent?

Q13: talk adapter mode

Q14: what is the difference between adapter mode and decorator mode and proxy mode?

Q15: stress strategy mode

Q16: talk about template mode

Q17: talk about observer mode


Sometimes I will ask the basic concept of design pattern, sometimes I will ask the specific content of design pattern or let you draw by hand, and sometimes I will ask what design patterns are used in the framework!

Q1: how many design patterns are there?

There are generally 23 design modes.

Create mode:

Factory method

Abstract factory pattern

Singleton mode

Builder mode (builder)

Prototype

Structural mode:

Adapter mode

Decorator mode

Proxy mode (proxy)

Appearance mode (facade)

Bridge mode

Composite mode

Flyweight mode

Behavioral mode:

Strategy

Template method

Observer mode (observer)

Iterator mode (iterator)

Chain of responsibility

Command mode (command)

Memo mode (memo)

State mode

Visitor mode

Mediator mode

Interpreter mode (interpreter)

Q2: what are the principles of design pattern?

Generally speaking, the principles of design pattern include dependency leading principle, single responsibility principle, interface isolation principle, opening and closing principle, Demeter method principle and Richter replacement principle. The principle diagram of design mode is as follows:

Q3: classification of design patterns. Which design patterns do you know?

Creation type: hide the creation logic while creating objects, so that ⽤ new does not directly instantiate objects. The program is more flexible in judging which objects need to be created. Including factory / abstract factory / singleton / builder / prototype pattern.

Structural type: create objects with complex structure through inheritance and introduction between classes and connectors. Including adapter / bridge mode / filter / combination / decorator / appearance / enjoy yuan / agent mode.

Behavioral: different behaviors are realized through different communication methods between classes. Including chain of responsibility / naming / interpreter / iterator / mediator / memo / observer / status / policy / template / visitor pattern.

The classification diagram is as follows:

 

Q4: simple mode

The simple factory mode refers to the creation of instances by ⼀ factory objects. The client does not need to pay attention to the creation logic, but only needs to provide the parameters passed to the ⼊ factory.

It is applicable to the case where the factory class is responsible for creating fewer objects. The disadvantage is that if you want to add new products, you need to modify the judgment logic of the factory class, which violates the opening and closing principle. If there are many products, the factory class will be more complex.

Calendar object of calendar abstract class. Method, call the method to create different beanfactories in spring according to different regional parameters, so as to make the simple factory mode, and obtain the bean object according to the unique ID passed.

Simple example:

/**

 *  Latte, American coffee and cappuccino are all products of the coffee family

 *  Coffee is an abstract concept

 * @ author 

 */

public abstract class Coffee {

    /**

     *  Get coffee name

     * @ return

     */

     public abstract String getName();

}


/**

 *  Cafe Americano

 * @ author Lsj

 *

 */

public class Americano extends Coffee {


    @ Override

     public String getName() {

         Return "American coffee";
    }

}


/**

 *  Cappuccino

 * @ author Lsj

 */

public class Cappuccino extends Coffee {


    @ Override

     public String getName() {

         Return "cappuccino";

    }

}


/**

 *  Latte

 * @ author Lsj

 */

public class Latte extends Coffee {

    @ Override

     public String getName() {

         Return "latte";
    }

}

Q5: speaking, speaking, and law mode

The factory method pattern refers to defining ⼀ connections for creating objects, allowing the connected implementation class to decide which object to create, and delaying the instantiation of the class to ⼦ class.

The client only needs to close the corresponding factory without closing the creation details. It mainly solves the problem of product expansion. In the simple mode, if there are more product types, the factory will have more and more responsibilities, which is not easy to maintain.

Collection defines ⼀ abstract factory methods in this abstract factory and returns ⼀ Abstract products of iterator class

Product. This ⽅ method is implemented through specific factories such as ArrayList and HashMap, and returns specific products such as ITR and keyiterator.

Spring's factorybean connection method is also a factory method.

Q6: what design patterns are used in the spring framework?

A large number of design patterns are used in the spring framework. Here are some representative ones:

1. Proxy mode - it is often used in AOP and remoting.

2. Singleton mode - the bean defined in the spring configuration file defaults to singleton mode.

3. Front end controller - spring provides dispatcherservlet to distribute requests.

Q7: do you understand the abstract ⼯ pattern?

Abstract factory pattern refers to providing ⼀ connections for creating ⼀ series of related or interdependent objects, and ⽆ specifying their specific classes.

The client does not depend on the details of how product class instances are created and implemented. It mainly depends on the situation that the system has more than ⼀ product families, and the system only consumes ⼀ product families. The disadvantage of abstract factory pattern is that it is inconvenient to expand product family, and increases the abstraction and understanding difficulty of the system.

Java.sql.connection is an abstract factory, including many abstract products, such as statement, blob, savepoint, etc.

public class AbstractFactoryTest {

    public static void main(String[] args) {

       //  Abstract factory

        String result = (new CoffeeFactory()).createProduct("Latte");

        System.out.println(result); //  Output: Latte

   }

}

//Abstract factory

abstract class AbstractFactory{

    public abstract String createProduct(String product);

}

//Brewery

class BeerFactory extends AbstractFactory{

   @ Override

    public String createProduct(String product) {

        String result = null;

        switch (product) {

            case "Hans":

                Result = "Hans";

                break;

            case "Yanjing":

                Result = "Yanjing";

                break;

            default:

                Result = "other beer";

                break;

       }

        return result;

   }

}

/\*\ * Coffee Factory\*/

class CoffeeFactory extends AbstractFactory{

   @ Override

    public String createProduct(String product) {

        String result = null;

        switch (product) {

            case "Mocca":

                Result = "Mocha";

                break;

            case "Latte":

                Result = "latte";

                break;

            default:

                Result = "other coffee";

                break;

       }

        return result;

   }

}

Q8: what are the characteristics of singleton mode?

The singleton mode belongs to the creation mode. In any case, there are only ⼀ instances of ⼀ singleton classes. The construction method must be private, create ⼀ static variable storage instances by yourself, and provide ⼀ static public methods to obtain instances.

The advantage is that there are only ⼀ instances in memory, which reduces the overhead, especially when instances are created and destroyed frequently, and avoids multiple reuse of resources. The disadvantage is that there is no abstraction layer, it is difficult to expand, and it conflicts with the single responsibility principle.

Bean instances created by spring's ApplicationContext are singleton objects, as well as ServletContext and database connection pool.

The UML class diagram is as follows:

 

Example implementation of singleton mode:

1 class Person{

  2 private:

  three       Person(){};

  four       Person(const Person&){};

  five

  six       static Person *Singleton; // Static variables, in class declarations, and out of class initialization. Static is not used during initialization, and the scope needs to be specified

  seven

  8 public:

  nine       static Person *getInstance(){

ten           return Singleton;

eleven      }

12 };

thirteen

14 Person *Person::Singleton = new Person;

fifteen

16 void test01(){

seventeen

eighteen       Person::getInstance();// Access singleton through external interface

nineteen       Person *p = Person::getInstance();

twenty       Person *p1 = Person::getInstance();

twenty-one

twenty-two      //--------------

twenty-three      // You cannot define or new instances directly. You can only call the interface

twenty-four      // Person p2;

twenty-five      // Person *p1 = new(*p); // The copy constructor is called here

twenty-six      //--------------

twenty-seven

twenty-eight       if (p == p1){

twenty-nine           Cout < < two singletons have the same address and are the same singleton < < endl;

thirty      }

thirty-one

32 }

Q9: what are the implementations of singleton mode?

Hungry Chinese style: it is thread safe to initialize and create a singleton object when the class is loaded, but creating objects regardless of whether ⽤ is enabled or not may waste memory.

Lazy type: it will be loaded only when it is externally adjusted. The thread is unsafe. It can be locked to ensure thread safety, but the efficiency is low.

Double check lock: make volatile and multiple checks to reduce the lock range and improve efficiency.

Static inner class: solve the memory waste problem of hungry man and thread safety problem of lazy man at the same time.

Enumeration: the ⽅ style advocated in E ff effective Java can not only avoid thread safety problems, but also prevent ⽌ deserialization and re creation of new objects, absolutely prevent ⽌ multiple instantiations, but also prevent ⽌ reflection and ing single cases.

Q10: talk about agent mode

The proxy mode belongs to the structural mode, which provides ⼀ proxies for other objects to control access to this object. The advantage is that it can enhance the function of (standard object, reduce code coupling and have good expansibility. The disadvantage is that adding a proxy object between the client and (target object will slow down the request processing speed and increase the system complexity.

Provide a proxy for other objects to control access to this object. Problems when accessing objects directly, for example, the object to be accessed is on a remote machine. In an object-oriented system, direct access to some objects will bring a lot of trouble to users or system structure for some reasons (such as high object creation cost, or some operations need security control, or need out of process access). We can add an access layer to this object when accessing this object.

The code of the specific proxy mode is as follows:

package com.Model.Proxy;



//Car buying behavior

public interface BuyCar {

     public void buycar();

}


package com.Model.Proxy;


public class People implements BuyCar {

     private int cash;

     private String vip;

     private String username;

    @ Override

     public void buycar() {

         System.out.println(username + " is vip so he/she can buy any car...");

    }


     public int getCash() {

         return cash;

    }



     public void setCash(int cash) {

         this.cash = cash;

    }


     public String getVip() {

         return vip;

    }


     public void setVip(String vip) {

         this.vip = vip;

    }


     public String getUsername() {

         return username;

    }


     public void setUsername(String username) {

         this.username = username;

    }


}


//Agent class to check whether the car buying behavior complies with the rules

class ProxyBuyCar implements BuyCar {

     private People People;

     public People getPeople() {

         return People;

    }

     public void setPeople(People people) {

         People = people;

    }


    @ Override

     public void buycar() {

         if (People.getVip().equals("vip")) {

             People.buycar();

        }  else if (People.getCash() >= 50000) {

             System.out.println(People.getUsername() + "buy a new car trade over...");

        }  else {

             System.out.println(People.getUsername() + "people can't buy a car ");

        }

    }
}

Spring uses ⽤ dynamic proxy to implement AOP. If the bean implements ⼝ JDK proxy, otherwise ⽤ cglib proxy.

Static proxy: the proxy object holds the reference of the proxy object. When calling the method of the proxy object, it will also call the method of the proxy object, but other logic will be added before and after the method of the proxy object. It needs to be completed. The bytecode of the proxy class already exists before the program runs. The relationship between the proxy class and the proxy class has been determined before the program runs. The disadvantage is that ⼀ proxy classes can only serve ⼀ targets. If multiple types of services are required, the workload will be increased.

Dynamic proxy: dynamic proxy creates a specific proxy class through reflection during program operation. The relationship between proxy class and proxy class is uncertain before operation. Dynamic agent has stronger adaptability, which is mainly divided into JDK dynamic agent and cglib dynamic agent.

JDK dynamic proxy: to obtain ⽅ dynamic proxy objects through the ⽅ method of classes, you need to pass ⼊ three parameters, the class loader of the proxy object, the connection implemented by the proxy object, and ⼀ to indicate the specific logic. The advantage of ⽐ static proxy is that all ⽅ methods declared in the connection ⽅ are transferred to the ⽅ method of call processing for centralized processing.

Cglib dynamic proxy: JDK dynamic proxy requires to implement the connection of the proxied object. Cglib requires to inherit the proxied object. If a class is a "nal class", cglib cannot be proxied. Both agents generate bytecode during the run-time. JDK dynamic agent writes node code directly. Cglib dynamic agent enables ASM framework to write node code. ASM's function is to generate, convert and analyze compiled Java classes represented by byte arrays. The JDK dynamic agent calls the proxy method through the reflection mechanism. The gclib dynamic agent calls the method directly through the fastclass mechanism. It forms a class for the proxy class and the proxy class. This class allocates int parameters to the method of the proxy class and the proxy class. When calling the method, it can be located directly. Therefore, it is more efficient.

Q11: talk about decorator mode

Let's first look at the structure diagram of the mode:

Decorator mode belongs to structural mode, which attaches functions to objects without changing the original objects. Phase inheritance can more flexibly expand the functions of the original objects.

The decorator pattern is suitable for scenarios: extend the functions of ⼀ classes without adding many ⼦ classes.

In the java.io package, the InputStream byte input stream is enhanced into a buffer byte input stream through the decorator bu "eredinputstream".

Q12: what is the difference between decorator mode and dynamic agent?

First, let's take a look at their class diagram:

 

The decorator pattern focuses on dynamically adding ⽅ methods to objects, and ⽽ dynamic agents pay more attention to object access control. Dynamic proxy usually creates an instance of the proxy object in the proxy class, and the decorator mode takes the decorator as a parameter of the constructor.

Q13: talk adapter mode

The adapter mode belongs to the structural mode. As a bridge between two incompatible connections, it combines the functions of two independent connections to convert the connections of ⼀ classes into another connection, so that classes that cannot be started due to incompatible connections can be started.

The disadvantage is that too many adapters will make the system often chaotic and difficult to grasp as a whole.

In java.io package, InputStream byte input stream is converted into reader character input stream through adapter inputstreamreader.

For the handleradapter in spring MVC, there are many forms of handlers, including controller, httprequesthandler, servlet, etc., but the calling method ⼜ is determined. Therefore, the adapter is required for ⾏ processing, and the ⽤ handle method is called according to the adaptation rules.

Arrays.aslist ⽅ method to convert the array into the corresponding set (note that ⽤ the ⽅ method of modifying the set cannot be used, because the returned ArrayList is ⼀ internal classes of arrays).

The code implemented by the adapter is as follows:

/\*\ * traditional charging cable microusb\*/

interface MicroUSB {

     void charger();

}

/\*\ * typec charging port\*/

interface ITypeC {

     void charger();

}

class TypeC implements ITypeC {

    @ Override

     public void charger() {

         System.out.println ("typec charging");

    }

}

/\*\ * adapter\*/

class AdapterMicroUSB implements MicroUSB {

     private TypeC typeC;

     public AdapterMicroUSB(TypeC typeC) {

         this.typeC = typeC;

    }

    @ Override

     public void charger() {

         typeC.charger();

    }

}

/\*\ * test call\*/

public class AdapterTest {

     public static void main(String[] args) {

         TypeC typeC = new TypeC();

         MicroUSB microUSB = new AdapterMicroUSB(typeC);

         microUSB.charger();

    }

}

Q14: what is the difference between adapter mode and decorator mode and proxy mode?

The adapter mode has no hierarchical relationship, and the adapter and the Adaptee are not necessarily continuous. It is a post consideration to solve the problem of incompatibility.

The decorator mode has a hierarchical relationship. The decorator and the decorated realize the relationship of "individual connection" and "full" is-a, and pay attention to coverage and expansion, which is a kind of pre consideration.

The adapter mode mainly changes the connection of the considered object, and the proxy mode cannot change the connection of the proxy class.

Q15: stress strategy mode

The policy pattern belongs to the behavior model pattern. It defines a series of algorithms and encapsulates them, which can be replaced with each other. The policy mode mainly solves the problem of difficult maintenance caused by ⽤ if / else when there are many similar algorithms.

The advantage is that the algorithm can be switched from one to another, can avoid using multiple conditional judgment, and has good scalability. The disadvantage is that the number of policy classes will increase, and all policy classes need to be exposed.

In the collection framework, it is often necessary to pass a comparator to compare and sort through the construction method. Comparator is

⼀ Abstract policies, ⼀ classes become concrete policy classes by implementing the connection and overriding the compare method.

When creating a thread pool, it is necessary to pass a reject policy. When a new thread is created so that the number of threads currently running exceeds the maximumpoolsize, it will be processed by the corresponding reject policy.

The code of policy mode implementation is as follows:


/\*\ * travel statement\*/

interface ITrip {

     void going();

}

class Bike implements ITrip {

    @ Override

     public void going() {

         System.out.println ("cycling");

    }

}

class Drive implements ITrip {

    @ Override

     public void going() {

         System.out.println ("start up");

    }

}

/\*\ * define travel class\*/

class Trip {

     private ITrip trip;



     public Trip(ITrip trip) {

         this.trip = trip;

    }



     public void doTrip() {

         this.trip.going();

    }

}

/\*\ * execution method\*/

public class StrategyTest {

     public static void main(String[] args) {

         Trip trip = new Trip(new Bike());

         trip.doTrip();

    }

}

Result of program execution: cycling

Q16: talk about template mode

The template mode belongs to the ⾏ as type mode, so that the ⼦ class can redefine some steps of the algorithm without changing the algorithm structure, which is suitable for extracting the repeated code of the ⾊ class to the public ⽗ class.

The advantage is that it can encapsulate fixed parts and expand variable parts. The disadvantage is that each different implementation requires maintenance of ⼀ classes, which will increase the number of classes.

In order to prevent malicious operations, general template methods are modified with "nal".

Httpservlet defines a set of templates for processing HTTP requests. The service method is the template method, which defines the basic process for processing HTTP requests. Doxxx and other methods are the basic methods. The corresponding processing is carried out according to the type of request method. The class can override these methods.

Q17: talk about observer mode

First look at the UML diagram of the observer pattern:

 

The observer mode belongs to the "for" mode, also known as the publish subscribe mode. It defines a "many to many" dependency between objects. When the state of an object changes, all objects that depend on it are notified and updated. It mainly solves the problem of notifying other objects when the state of one object changes. The disadvantage is that if the observed object has many direct and indirect observers, the notification is time-consuming. If there is circular dependency, it may lead to system crash. In addition, the observer can't know how the target object changes.

The servletcontextlistener can listen to the "life cycle" of the ServletContext object, which is actually listening to the Web response. When the servlet container starts the web, it should call the contextinitialized method and the contextdestroyed method at the end.

I hope everyone can master the design mode as soon as possible, so that they won't be afraid of the interview questions of design mode in the interview.

Previous classic articles:

1,❤️ liver failure! Sorted out the spring interview [including answers] for a week and hanged the Java interviewer [suggestions collection]! ❤️

2,❤️ When the liver is over, master the data structure and algorithm one day, interview questions, hang the interviewer, and suggest collecting ❤️

3,❤️ Is the collection simple? Are you kidding? Liver for a week, is the essence, all words to explain! Interview is no longer afraid of questions!!! ❤️

4,After that, I summarized the knowledge points of springboot and cache, and quickly mastered them

5,MySQL interview encyclopedia, after reading it, you can hang and beat the interviewer!!!

6,Junior brothers and sisters majoring in computer, don't be confused. I'll sort out a complete collection of CS learning routes! Help you surpass most of your classmates!

7,❤️ Junior college background, get Ali offer, Xiao Meng calls 666【 [hard core interview] ❤️

I'm Xiao Meng. Remember to give me a compliment. Thanks!

Little friends like, collect and comment, and walk up three times with one button. See you next time~~

Reference books:

Headfirst design pattern

emoticon
Insert expression
Relevant recommendations More similar content
©️ 2020 CSDN Skin theme: technical blackboard Designer: CSDN official blog Return to home page
Paid inelement
Payment with balance
Click retrieve
Code scanning payment
Wallet balance 0

Deduction Description:

1. The balance is the virtual currency of wallet recharge, and the payment amount is deducted according to the ratio of 1:1.
2. The balance cannot be purchased and downloaded directly. You can buy VIP, c-coin package, paid column and courses.

Balance recharge
mbapedia4.com