I. Classification of design patterns

Generally speaking, design patterns can be divided into three categories:

There are five types of creation patterns: factory method pattern, Abstract factory pattern, singleton pattern, Builder pattern, and prototype pattern.

Structural mode, a total of seven: adapter mode, decorator mode, agent mode, appearance mode, bridge mode, composite mode, share mode.

There are eleven behavioral modes: strategy mode, template method mode, observer mode, iteration sub-mode, responsibility chain mode, command mode, memo mode, state mode, visitor mode, intermediary mode, interpreter mode.

Second,Design patternsThe principle of

1. Open Close Principle
The open closed principle means open for extensions, closed for modifications. When the program needs to be extended, you cannot modify the original code to achieve a hot plug effect. So a word summary is: in order to make the program expansibility, easy to maintain and upgrade
2. Liskov Substitution Principle
One of the basic principles of object-oriented design. Richter’s rule of substitution says that wherever a base class can appear, a subclass must appear.
3, Dependence Inversion Principle
This is the basis of the open and close principle. The specific contents are :(1)
A high-level module should not depend on a low-level module; both should depend on its abstraction (2)
Abstractions should not depend on details (3)
Details should depend on abstractions
4. Interface Segregation Principle
This principle means that it is better to use multiple isolated interfaces than a single one. From here, we can see that in fact, design mode is a software design idea, starting from large software architecture, in order to upgrade and maintenance convenience. So many times above: reduce dependency, reduce coupling.
5. Demeter Principle
Why is it called the least known principle? That is, an entity should interact with other entities as little as possible, so that the functional modules of the system are relatively independent.
Composite Reuse Principle
The rule is to use composition/aggregation rather than inheritance whenever possible

Three,Creation pattern

1. Single column mode

Lazy mode: load only when it is actually created (load on demand), there are thread safety issues, need to add a thread lock. (2), hanhanmode: after the system is started, it is loaded successfully, and there is no thread safety problem. (3), enumeration: the key comes, banging on the board, in the above mode will have radial mechanism and serialization and other ways to make the single column invalid, and then use the single column mode as follows:

public enum EnumSingleton { INSTANCE; public EnumSingleton getInstance(){ return INSTANCE; }}Copy the code
Simple, minimal code, and secure, so you get the idea.
2. Factory Method Pattern — (single product)
interface Computer{ void printComputer(); } class MacbookPro implements Computer{ public void printComputer(){ System.out.println("This is a macbookpro"); } } class SurfaceBook implements Computer{ public void printComputer(){ System.out.println("This is a Surfacebook"); }} class MsFactory implements ComputerFactory{public Computer creatComputer(){return new SurfaceBook(); Class AppleFactory implements ComputerFactory{public Computer creatComputer(){return new MacbookPro(); Interface ComputerFactory{Computer creatComputer(); } public class Test19{ public static void main(String[] args){ ComputerFactory factory = new AppleFactory(); Computer computer = factory.creatComputer(); computer.printComputer(); }}Copy the code

Factory method pattern: Defines an interface for creating objects and lets subclasses decide which factories to instantiate.

Advantages: reduces the coupling of the code, object to the subclass to complete Implement the open closed principle, each added products do not need to modify the original code faults: increased the amount of code, each concrete product requires a specific plant When adding the abstract product, also is to add a product family, other need to modify the factory,

2. Abstract Factory Pattern — (Abstract, implementation)

interface Computer{
    void printComputer();
}
class MacbookComputer implements Computer{
    public void printComputer(){
        System.out.println("This is a Macbookpro");
    }
}
class SurfaceBookComputer implements Computer {
    public void printComputer() {
        System.out.println("This is a Surfacebook");
    }
}
interface OperatingSystem{
    void printSystem();
}
class MacOsSystem implements OperatingSystem{
    public void printSystem(){
        System.out.println("This is a mac os");
    }
}
class Windows8System implements OperatingSystem{
    public void printSystem() {
        System.out.println("This is a Window 8");
    }
}
interface  ProductionFactory{
    Computer createComputer();
    OperatingSystem createSystem();
}
class AppleFactory implements ProductionFactory{
    public Computer createComputer(){
        return new MacbookComputer();
    }
    public OperatingSystem createSystem(){
        return new MacOsSystem();
    }
}
class MsFactory implements ProductionFactory{
    public Computer createComputer(){
        return new SurfaceBookComputer();
    }
    public OperatingSystem createSystem(){
        return new Windows8System();
    }
}
public class Client{
    public void buyComputer(Computer computer){
        computer.printComputer();
    }
    public void use(OperatingSystem s){
        s.printSystem();
    }

    public static void main(String[] args) {
        Client client = new Client();
        ProductionFactory factory = new AppleFactory();
        Computer computer = factory.createComputer();
        OperatingSystem system = factory.createSystem();
        client.buyComputer(computer);
        client.use(system);
    }
}
Copy the code
Abstract Factory pattern: Provides an interface to create a series of related or interdependent objects without specifying their concrete classes. The factory method pattern is similar to the abstract factory pattern in that the factory method pattern is when the factory produces only one product, and the abstract factory pattern is when the factory produces two or more goods.

Advantages: Code decoupling enables multiple product families to meet the OCP open and closed principle and is flexible and extensible for production of complex objects. Disadvantages: Extending product families is cumbersome because all factories need to be modified. Since the slack factory pattern is an extension of the factory method pattern, it is generally cumbersome

4. Builder Mode – (Combo)

The factory class pattern provides a pattern to create a single class, while the builder pattern is to centralize the management of various products to create composite objects. The so-called composite objects mean that a class has different attributes. In fact, the builder pattern is the combination of the abstract factory pattern and the final Test. Let’s look at the code:

As before, there is a ComputerFactory interface and two implementation classes, AppleFactory and MsFactory. Finally, the builder class is as follows:

public class Builder { private List<ComputerFactory> list = new ArrayList<ComputerFactory>(); public void AppleComputerFactory(int count){ for(int i=0; i<count; i++){ list.add(new AppleFactory()); } } public void MsComputerFactory(int count){ for(int i=0; i<count; i++){ list.add(new MsFactory()); }}}Copy the code

The test class:

public class Test { public static void main(String[] args) { Builder builder = new Builder(); builder.AppleComputerFactory(10); }}Copy the code

From this point of view, the Builder pattern integrates a lot of functionality into a class that can create something complex. So the difference from the engineering pattern is that the factory pattern focuses on creating a single product, while the Builder pattern focuses on creating conforming objects, multiple parts. Therefore, the choice between the factory model and the builder model depends on the actual situation.

5. Prototyping

Prototype mode is also used in many scenarios in our actual development. I mainly have the following two scenarios in the actual development:

1. We want the next class operation to have no effect on the previous class operation;

2, usually in the asynchronous operation to avoid multi-threading problems, in the call method when do not want to be called method on the operation of the object to affect the rest of the layer of business logic processing;

If I need to do that, can I just new an object and assign it to myself instead of using the prototype mode?

Of course, as long as you don’t mind the trouble, the predecessors provided us with the prototype model must be because the prototype model is very good for us, generally speaking, the prototype model brings us the following benefits:

1. Program running efficiency: it can save the time of new object creation.

2. Code development efficiency: It can be done with a Clone () method without complex assignment operations

3. Stability of code: after code assignment one by one, will a subtle code bug be released due to a Cv operation error?

However, in actual development, when we need to use the prototype mode, we need to clone the object model, which is not very friendly;

What? Not friendly?

Second, I just need a clone object, also need to implement a bunch of complex shallow clone, deep clone code? Isn’t that a little too exhausting? Yes, I’m lazy as a programmer;

At this time. If we use org springframework. Beans. BeanUtils copyProperties of one line of code directly, then done.

Beanutils.copyproperties (" pre-converted class ", "converted class ");Copy the code

Summary: In terms of actual development:

Use enumerations for single columns (simple and practical); Factory pattern, one easy to write but hard to change (factory method), one easy to change but more detailed to write at first (abstract factory); The builder model is a combination of previously existing factories; The prototype pattern, in fact, is a copy, a simple summary of the above code.