Fragmentary knowledge points of design pattern
1. Two themes of design pattern: system reuse and system expansion
2. Design pattern is generally used to solve the problem of different appearance of the same problem
3. Software model is the bridge between software development engineers and software analysis designers
4. Design patterns are divided into: creation pattern, behavior pattern and structure pattern
Design pattern UML diagram
Six principles of design mode
- Single responsibility: a class is only responsible for one corresponding responsibility. There is only one reason that will cause class changes
- Opening and closing principle: a class is open to extension and closed to modification. When adding update functions, it does not modify the source code, and uses more interfaces and abstract classes
- Richter substitution principle: all references to a base class must be able to use its subclasses
- Dependency Inversion Principle: high-level modules should not rely on low-level modules, but should rely on their abstraction. Programming should be object-oriented rather than process-oriented
- Interface isolation principle: multiple interfaces should be used to replace the total interface
- Dimitri's Law: if you don't talk to strangers, one class should have as little contact with other classes as possible
Design mode - 23 modes:
- Factory mode
Intention: define an interface for creating objects, and let its subclasses decide which factory class to instantiate. The factory pattern delays the creation process to the subclasses.
Disadvantages: it violates the opening and closing principle. If a new class is generated, the source code needs to be modified
Modification method: change the switch statement of the original factory mode to class reflection to create a class
- Abstract factory pattern
Intent: provide an interface to create a series of related or interdependent objects without specifying their specific classes. A factory can create classes of multiple categories.
- Singleton mode
Intent: ensure that a class has only one instance and provide a global access point to access it.
Disadvantage: cannot be inherited because the constructor is private
Several creation methods (refer to rookie tutorial)
-
Hungry Han style:
Description: class is initialized upon loading
Advantages: no lock, high efficiency and thread safety
Disadvantages: class is created upon loading, which wastes resources
code:
public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } }
-
Lazy / wireless security:
Description: the most basic and basic singleton mode is created and initialized only when called
Disadvantages: lack of thread safety
-
Lazy / thread safe:
Description: Based on the traditional lazy mode, use synchronized to lock
Disadvantages: low efficiency, no need to lock in most cases
code:
public class Singleton { private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
-
Double check lock / double check lock
Description: this method adopts double lock mechanism, which is safe and can maintain high performance in the case of multithreading.
Advantages: instead of locking the method, the double locking mechanism is used internally to judge whether a single instance is created, which greatly improves the performance of a single instance
code:
public class Singleton { private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
-
Registered / static inner class
Description: the static internal class is used to achieve the effect of delaying the loading of a single instance. Different from the hungry Han type, the hungry Han type initializes when the class is loaded, while the registration type does not initialize when the class is loaded. It initializes when your static internal class is accessed, which also ensures thread safety
code:
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; } }
- Responsibility chain model
Description: avoid coupling the sender and receiver of the request, make it possible for multiple objects to receive the request, connect these objects into a chain, and pass the request along the chain until an object processes it.
- Intermediary model
Description: a series of object interactions are encapsulated with a mediation object by using the Demeter's law. The mediator makes the objects do not need to explicitly refer to each other, so that their coupling is loose, and the interaction between them can be changed independently.
Example: all users do not communicate directly, but send what they want to say to the chat room for information transmission
- Strategy mode
Description: define a series of algorithms, encapsulate them one by one, and make them replaceable
- Adapter mode
Description: two unrelated classes are adapted and transformed, and the information of class A is transformed into the pattern of class B
Example: 220v voltage is adopted in China and 110v voltage is adopted abroad. It is necessary to bring Chinese electrical appliances abroad for use and use voltage converter (adapter) for conversion
Disadvantages:
① Excessive use of adapter classes can cause code to become very messy.
② Because java inheritance can only be one, an adapter can only implement one adapter class.
Code:
Target interface
public interface Target { //This is a method that the source class Adapteee does not have public void Request(); }
Source class (Adaptee needs to be adapted)
public class Adaptee { public void SpecificRequest(){ } }
adapter class
//The Adapter inherits from the Adaptee and implements the target interface. public class Adapter extends Adaptee implements Target { //The target interface requests to call the method name Request(), but the source class Adaptee has no method Request() //Therefore, the adapter is supplemented with this method name //But in fact, Request() is only the content of calling the SpecificRequest() method of the source class Adaptee //Therefore, the adapter just encapsulates the SpecificRequest() method into a Request() that the Target can call @Override public void Request() { this.SpecificRequest(); } }
- Appearance mode
Description: allows the client to access an interface of the system side and provides a consistent interface for a group of interfaces in the subsystem. The appearance mode defines a high-level interface, which makes the subsystem easier to use.
advantage:
1. Reduce system interdependence.
2. Increase flexibility.
3. Improved security.
Disadvantages: it does not comply with the opening and closing principle. If it is troublesome to change things, inheritance and rewriting are inappropriate.
- Bridging mode
Description: separate the abstract part from the implementation part so that they can change independently. Put an interface instance in an abstract class.
- Builder pattern
Intention: construct simple class objects into a complex combination, and the same construction process can create different combinations
Advantages: easy to expand, independent, and greatly reduce the construction method
Disadvantages: products must have something in common and the scope is limited. If the internal changes are complex, there will be many construction classes
- Command mode
Intent: encapsulate a request into an object so that you can parameterize the customer with different requests.
Example: the computer is the person who accepts the command, and the user is the person who issues the command. Each key is packaged into a command and sent to the computer
Advantages: it conforms to the opening and closing principle, and can be withdrawn and returned without modifying the original class itself
Disadvantages: using command mode may cause some systems to have too many specific command classes
- Iterator mode
Description: separate the traversal methods in the aggregate class, and enable external code to traverse and obtain the data in the aggregate class transparently while ensuring that the internal structure is not exposed
Advantages: 1. It supports traversing an aggregate object in different ways. 2. Iterators simplify aggregate classes. 3. There can be multiple traversals on the same aggregate. 4. In iterator mode, it is convenient to add new aggregate classes and iterator classes without modifying the original code.
Disadvantages: because the iterator mode separates the responsibilities of storing data and traversing data, adding new aggregate classes requires adding new iterator classes correspondingly, and the number of classes increases in pairs, which increases the complexity of the system to a certain extent.
public class NameRepository implements Container { public String[] names = {"Robert" , "John" ,"Julie" , "Lora"}; @Override public Iterator getIterator() { return new NameIterator(); } private class NameIterator implements Iterator { int index; @Override public boolean hasNext() { if(index < names.length){ return true; } return false; } @Override public Object next() { if(this.hasNext()){ return names[index++]; } return null; } } }
- State mode
Intent: allows an object to change its behavior when its internal state changes, and the object looks as if it has modified its class.
Advantages: 1. It encapsulates the conversion rules. 2. Enumerate possible states. Before enumerating States, you need to determine the state type. 3. Put all the behaviors related to a state into one class, and you can easily add new states. You can change the behavior of the object only by changing the state of the object. 4. Allow state transition logic to be integrated with state objects rather than a huge conditional statement block. 5. Multiple environment objects can share a state object, thus reducing the number of objects in the system.
Disadvantages:
1. The use of state mode will inevitably increase the number of system classes and objects.
2. The state mode does not support the "opening and closing principle" very well. For the state mode that can switch states, adding a new state class requires modifying the source code responsible for state transition, otherwise it cannot switch to the new state, and modifying the behavior of a state class also requires modifying the source code of the corresponding class.
- Combination mode
Intent: combine objects into a tree structure to represent a "part whole" hierarchy. The combination mode makes the user's use of single objects and combined objects consistent.
advantage:
1. Clear structure and simple calling of high-level modules
2. Nodes can be added freely
Disadvantages:
It does not conform to the dependency inversion principle. All are expressed in the form of classes
- Template method pattern
Description: defines the skeleton of an algorithm in an operation, and delays some steps to subclasses. Template method allows subclasses to redefine some specific steps of an algorithm without changing the structure of the algorithm. (there's nothing to say about inheritance)
Note: in order to prevent malicious operations, the general template method adds the final keyword.