There are six principles of design patterns

  • Single Responsibility Principle
  • Liskov Substitution Principle
  • Dependence Inversion Principle
  • Interface Segregation Principle
  • Law of Demeter
  • Composite Reuse Principle

There are three broad categories of design patterns

  1. The Creational Pattern abstracts the instantiation process of a class, separating the creation and use of objects in a software module.

(5) Factory pattern, Abstract factory pattern, singleton pattern, Builder pattern, prototype pattern

  1. Structural Pattern: focuses on the composition of objects and the dependence between objects, and describes how to combine classes or objects together to form a larger structure. Just like building blocks, complex and more powerful structures can be formed through the combination of simple blocks.

(7) Adapter mode, decorator mode, agent mode, appearance mode, bridge mode, combination mode, share mode

  1. Behavioral Pattern: It focuses on the behavior of objects and abstracts the division of responsibilities and algorithms among different objects. Focus not only on the structure of classes and objects, but also on the interactions between them.

(11) Policy mode, template method mode, observer mode, iterator mode, Responsibility chain mode, command mode, memo mode, state mode, visitor mode, mediator mode, interpreter mode

Simple Factory model

A factory returns different products based on different parameters

Fruit shop is understood as a simple factory, you ask for apples, he gives you apples, you ask for pears, he gives you pears.

The factory pattern

A factory creates a concrete product, and a product corresponds to a factory class.

BMW X1 has one factory class, X2 has one factory class, X3 has one factory class, Mercedes-benz A-class has one factory class, AND C-class has one factory class

Abstract Factory pattern

A factory creates a class of products, and a class of products corresponds to a factory.

For example, a car manufacturing factory is an abstract factory, which can produce BMW X1, X2 and X3. A cannery is an abstract factory that can produce canned oranges as well as canned peaches.

The singleton pattern

This is not a big deal, ensuring that a class has only one instance and providing a global access point to it. The lazy and hungry are the ones to remember. Lazy: instantiate only when needed. Common examples are non-null and double-checked implementations. Hungry: Instantiate the class when it is loaded. Something like this

private static Singleton instance = new Singleton();
Copy the code

Hungry is thread safe. The mainstream approach we use is the static inner class approach.

public class SingleInstance{
  private SingleInstance(a){}
 
  private static class SingleInstanceHolder{
     private static SingleInstance INSTANCE = new SingleInstance();
 }
 
  public static SingleInstance getInstance(a){
    returnSingleInstanceHolder.INSTANCE; }}Copy the code

Each province will have only one governor.

Builder model

It’s the Builder model that we use. Using multiple simple objects to build a complex object step by step can simplify the construction process of complex objects. Separating a complex build from its representation allows the same build process to create different representations.

  1. AndroidIn theDialogCreation is the typical builder pattern.
  2. Like a jigsaw puzzle, you can put it in any order, but you always end up with the same thing.

The prototype pattern

Used to create duplicate objects while maintaining performance. Copy your own object internal implementation of a prototype interface, used to create your own clone of the object.

  1. Shadow copy
  2. Java Object of clone ()

Adapter mode

A bridge between two incompatible interfaces. Translate the interface of a class into another interface that the customer wants. The adapter pattern makes it possible for classes to work together that would otherwise not work because of interface incompatibilities.

The power plug of port edition is big head of British mark, domestic insert row is the small mouth of national standard, need to buy a converter, this converter is adapter.

The proxy pattern

There are static proxy and dynamic proxy. Static will have a static proxy class, and dynamic is mainly implemented at runtime through reflection. In the proxy mode, we create objects with existing objects to provide functional interfaces to the outside world.

  1. Shortcuts in Windows
  2. When the emperor was in the early dynasty, the eunuch sent messages to the emperor, and between the emperor -> eunuch -> ministers, the eunuch was equivalent to acting.

The bridge model

The pattern of decoupling abstraction from implementation so that the two can vary independently involves an interface that acts as a bridge, making the function of the entity class independent of the interface implementation class.

The switch on the wall and the light in the ceiling, when the switch is pressed, the light bulb goes off, when the switch is pressed again, the light bulb comes on again. The states between them are independent. Like switches, which can be turned on and off, and light bulbs, which can be turned on and off. But they’re coupled, so when the switch is off, the bulb goes off, and when it’s on, the bulb goes on. So we are the clients, and the switch and the bulb are the decoupling of abstraction and implementation.

Portfolio model

Also known as the partial global pattern, it is used to treat a group of similar objects as a single object. The composite pattern combines objects based on a tree structure, which is used to represent both part and whole hierarchies. This pattern creates a class that contains its own group of objects. This class provides a way to modify the same object group.

  1. A group company usually has a head office at the top, with administrative and R&D departments and branches below, which in turn have departments. This creates a tree structure.
  2. In the AndroidViewGroup.View.ButtonThe relationship between etc is also a combination mode.

Decorator mode

Allows you to add new functionality to an existing object without changing its structure. This pattern creates a decorator class that wraps the original class and provides additional functionality while preserving the integrity of the class method signature.

  1. A picture was framed to make a decorative picture.
  2. It is uncivilized behavior for human beings not to wear clothes, and they become civilized people by wearing clothes. Clothes also give you extra features, like pockets.

Extension: What is the difference between decorator mode and proxy mode? Simple understanding: They both wrap the original object, but the proxy mode tends to control permissions. Generally speaking, we don’t want clients to have direct access to the target object or we don’t want clients to have direct access to the target object. With the proxy mode (which can also be enhanced within the proxy class), the decorator mode allows us to freely access the decorator class and the original target class wrapped by the decorator class. The decorator class provides much more power.

The appearance model

Hiding the complexity of the system and providing an interface through which the client can access the system. This pattern involves a single class that provides simplified methods for client requests and delegate calls to existing system class methods.

  1. To see a doctor in the hospital, you need to register, draw blood, take medicine and so on. The process is very complicated. The hospital provides a receptionist, who helps you deal with all the procedures, you just need to concentrate on seeing the doctor.
  2. AndroidImage loading libraryGlide, a line of code to help you achieve the image download and display, hidden complex image display logic.
  3. We use mobile phones, including calls, cameras, games, a variety of functions. Don’t you make a phone call use a landline, take pictures take a camera, play video games buy my NS.

The mediator pattern

Used to reduce the complexity of communication between multiple objects and classes. This pattern provides a mediation class that typically handles communication between different classes and supports loose coupling, making code easy to maintain.

  1. We went to rent a house. If we were too tired to go to the landlord for direct rent, we would find an intermediary and the intermediary would find the landlord. Finally, we could rent a house through the intermediary.
  2. The technical middle platform we talk about is also an intermediary model from the whole point of view. Before the middle platform, our business logic is coupled with each other and chaotic. After the middle platform,clientandserverInteraction through the central platform.
  3. Users -> operators -> programmers, these three can also form a mediator model, operators from users to obtain program problems, feedback to the programmer to modify. Operations people are intermediaries.

Extended: What is the difference between the facade pattern and the mediator pattern? The facade pattern adds classes to encapsulate and simplify complex business logic into something easier to use. The mediator pattern hides complex coupling between multiple callers through mediation classes, with the mediator working separately with the originally coupled classes.

The flyweight pattern

It is used to reduce the number of objects created to reduce memory usage and improve performance. The meta-share pattern attempts to reuse existing objects of the same class, and if no match is found, new objects are created.

  1. JAVAIn theStringIf not, create a string and store it in the string cache pool.
  2. Database connection pool
  3. The thread pool

Chain of Responsibility model

A chain of recipient objects is created for the request. In this pattern, each receiver typically contains a reference to the other receiver. If an object cannot handle the request, it passes the same request to the next recipient, and so on.

  1. AndroidEvent distribution mechanism in
  2. Beat the drum and pass the flowers
  3. As for the approval process for asking for leave, your leader will start the approval process step by step.

Template pattern

An abstract class exposes a method/template that executes its methods. Its subclasses can override method implementations as needed, but the calls will be made in the manner defined in the abstract class.

  1. The order in which you build a house, you have to lay the foundation, you have to build the body, you have to follow the plan step by step, you can’t do the other way around.
  2. AppFor the life cycle, that must be start-run-destroy
  3. Spring Festival gala prepared program, must be installed in order to perform.

Extension: What is the difference between the chain of responsibility model and the template model? The chain of responsibility is a hierarchy of different modules that can be executed from anywhere. Template patterns must be executed sequentially in a specified manner.

Command mode

Is a data-driven design pattern in which requests are wrapped in an object in the form of commands and passed to the calling object. The calling object looks for a suitable object that can handle the command and passes the command to the corresponding object, which executes the command.

  1. Trump issued a banTikTok“, the relevant departments below began to execute. Trump’s orders are issued and the department below is the enforcer.

The strategy pattern

The behavior of a class or its algorithm can be changed at run time. In the policy pattern, we create objects that represent various policies and a context object whose behavior changes as the policy object changes. The policy object changes the execution algorithm of the context object.

  1. Travel and choose transportation. Airplanes, high-speed trains, etc.
  2. There are many ways to sort an array, such as insert, merge, and bubble. Provides a unified interface to implement different sorting algorithms.
  3. B station to watch the video, switch to different resolutions (720,1080, tianlong people only enjoy blue light)

Memo mode

Save some state of an object so that the object can be restored at an appropriate time.

  1. The game file
  2. Transaction management of the database
  3. atomic
  4. Before modifying a file, create a backup file and delete the backup file if the modification succeeds

Observer model

The observer pattern is used when there is a one-to-many relationship between objects. When an object is modified, dependent objects are automatically notified.

  1. At the scene of a football match, the audience is the observer and the referee is the observed. After a foul or a goal is scored, the referee makes a decision and synchronizes the state to the audience.
  2. RSS feeds, where everyone subscribs to the same RSS address and when the content changes, the subscriber can see the changes.

Interpreter mode

Provides a way to evaluate a language’s syntax or expression. This pattern implements an expression interface that interprets a particular context. This pattern is used in SQL parsing, symbol processing engines, and so on.

  1. For example, weMavenConfiguration file ofxmlThere’s a lot of tags in there, and the program needs to have an interpreter to tell you what does each tag mean
  2. A common configuration file requires a parser to parse the meaning of each configuration.

Iterator pattern

This pattern is used for sequential access to the elements of a collection object without knowing the underlying representation of the collection object.

  1. In JAVA iterator
  2. On the first day of the New Year, line up to get red envelopes and go to the boss’s office one by one.

The state pattern

The behavior of a class changes based on its state. In state mode, we create objects that represent various states and a context object whose behavior changes as the state object changes. Different states have different behaviors.

  1. When a man is playing sports, he can walk, run and jump.
  2. TV and remote control. When the TV is turned off, the remote control can only control the START of the TV, and other buttons are invalid. Under the boot state, the remote control can be turned off, adjust channels, tune volume and so on.
  3. Inside the phonewifiSet, switch off,wifiThe function is disabled. Open it and look for itwifiSignal, connectionwifi

Visitor pattern

Design patterns that separate data operations from data structures. In the Visitor Pattern, we use a Visitor class that changes the execution algorithm of the element class. In this way, the element’s execution algorithm can change as visitors change. According to the schema, the element object already accepts the visitor object so that the visitor object can process operations on the element object.

In the company’s year-end performance assessment, the CEO and CTO separately assess non-technical and technical indicators. Non-technical and technical assessment indicators are different and can be divided into two sets. The CEO only needs to focus on the non-technical set and the CTO on the technical set.