Design patterns

Single responsibility principle

Open closed Principle A software entity such as classes, modules, and functions should be open for extension and closed for modification

All references to a base class must be able to transparently use objects from its subclasses

Demeter’s Law If two software entities do not communicate directly, then direct calls to each other should not occur and can be forwarded by a third party. Its purpose is to reduce the degree of coupling between classes and improve the relative independence of modules.

Interface isolation principle 1. Clients should not rely on interfaces that they do not need. 2. Dependencies between classes should be built on the smallest interface

The dependency inversion principle 1. Upper-level modules should not depend on lower-level modules, they should all depend on abstractions. Abstract should not depend on details, details should depend on the abstract.

The Abstract Factory pattern provides an interface for creating a series of related or interdependent objects without specifying their concrete classes. Principle: LSP Richter replacement principle

Scenario: Create different product objects and the client should use different specific factories.

Advantages:

A) Different product configurations can be used by changing the specific factory, making it easy to change the specific factory of an application. B) Separate the concrete instance creation process from the client, which operates on the instance through an abstract interface, and the concrete class name of the product from the implementation of the concrete factory.Copy the code

Disadvantages: If you want to add methods, change greatly.

Application:

A) The code in the JDK to connect to a database is typical of the abstract factory pattern. Each database provides a unified interface: a Driver (factory class) and implements its methods. Both JDBC and ODBC can extend the product line to achieve ways to connect to their own databases. B) The java.util.collection interface defines an abstract iterator() method, which is a factory method. The Collection is an abstract factory for the iterator() method.Copy the code

Builder pattern: Separate the construction of a complex object from its representation, so that the same construction process can create different representations. Principle: Rely on the inversion principle

Scenario: If the construction of a complex object needs to be separated from its representation, so that the same construction process can create different representations. The Builder pattern is the pattern that applies when the algorithm that creates complex objects should be independent of the components of that object and how they are assembled.

Advantages: It separates the build code from the presentation code.

Disadvantages: 1, increase the amount of code; 2. Builder is only an alternative to a constructor and cannot be used directly to reduce the number of arguments to a non-constructor method.

Application: StringBuilder and StringBuffer append() methods

The Factory Method pattern defines an interface for creating objects and lets subclasses decide which class to instantiate. The Factory Method delays the instantiation of a class to its subclasses. Principle: Open and closed principle

Scenario: Do not change the factory or product system, just extend the product (change).

Advantages: It is a further abstraction and extension of the simple factory pattern, while maintaining the advantages of the simple factory pattern (factory class contains the necessary logical judgment, according to the client selection conditions of the dynamic instantiation of related classes. For clients, it removes the dependency on specific products) and overcomes the disadvantages of simple factories (which violate the open and closed principle).

Disadvantages: For each additional product, a new product factory class needs to be added, adding additional development. (Can be solved by reflection).

Application:

  1. An iterator method in a Collection;Copy the code
  2.   java.lang.Proxy#newProxyInstance()
    Copy the code
  3.   java.lang.Object#toString()
    Copy the code
  4.   java.lang.Class#newInstance()
    Copy the code
  5.   java.lang.reflect.Array#newInstance()
    Copy the code
  6.   java.lang.reflect.Constructor#newInstance()
    Copy the code
  7.   java.lang.Boolean#valueOf(String)
    Copy the code
  8.   java.lang.Class#forName()
    Copy the code

Prototype pattern: Specifies the type of object to create with Prototype instances and creates new objects by copying those prototypes. Principle:

Scenario: Clone is used to copy initialization information without changing it.

Advantages: Hides object creation details, greatly improving performance. Instead of reinitializing the object, the state of the object at run time is obtained dynamically.

Disadvantages: Deep copy or shallow copy.

Application: Date class in JDK.

The Singleton pattern guarantees that a class has only one instance and provides a global access point to it. Principle: Encapsulation

Scenario: In general, we can have a global variable that makes an object accessible, but it doesn’t prevent you from instantiating multiple objects. One of the best ways to do this is to make the class itself responsible for holding its unique instance. This class guarantees that no other instances can be created, and it provides a method to access that instance.

Advantages: Controlled access to a unique instance.

Disadvantages: Hungry/lazy multithreading may cause multiple instances of simultaneous access.

Application: java.lang.runtime; There are also some in the GUI (java.awt.Toolkit#getDefaultToolkit() java.awt.desktop #getDesktop())

Adapter patterns transform the interface of a class into another interface that the customer expects. The Adapter pattern enables classes to work together that would otherwise not work together due to interface incompatibilities. In the GoF design pattern, there are two types of adapters, the class adapter pattern and the object adapter pattern.

A) class adapter pattern: matches one interface with another through multiple inheritance. C#, Java, and other languages do not support multiple inheritance, i.e. a class has only one parent class. B) Java generally refers to the object adapter patternCopy the code

Scenario: The adapter is used to reuse some existing classes. The data and behavior of the system are correct, but the interface does not match, so the adapter mode is used to make the original object and the new interface match.

Advantages: Can reuse existing classes, clients unified call the same interface, more simple, direct, compact.

Cons: The adapter pattern is a bit of a “never too late” experience and should be avoided during design.

Application: In the Java JDK, the adapter pattern is used in many ways, Such as collection package in Java. Util. Arrays# asList (), IO package in Java. IO. InputStreamReader (InputStream), Java. IO. OutputStreamWriter (OutputStream), etc

The Bridge pattern separates the abstract part from its implementation, allowing them to change independently. Principle: synthesis/polymerization reuse principle

Scenario: The implementation system may have multiple classifications, each of which may vary, so separate these classifications and allow them to vary independently, reducing the coupling between them.

Advantages: Reduced coupling of parts. Separation of abstraction and implementation, better scalability, dynamic implementation switching, can reduce the number of subclasses.

Disadvantages: 1. The introduction of bridge mode will increase the difficulty of understanding and designing the system. Since the aggregation association relationship is established at the abstraction layer, developers are required to design and program for abstraction. 2. Bridge mode requires the correct identification of two independent changing dimensions in the system, so its application scope has certain limitations

Application: the sort() method in the Collections class; AWT. JDBC database access interface API;

Composite combines objects into a tree structure to represent a partial-whole hierarchy. Scenario: The composite pattern should be considered when a requirement embodies a partial and overall hierarchy, and when you want users to use all objects in a composite structure uniformly, regardless of the differences between a composite object and a single object.

Advantages: Composite pattern lets customers use composite structures and single objects consistently.

Disadvantages: More abstract design, complex business rules for objects can be challenging to implement composite patterns, and not all methods are associated with leaf object subclasses.

Application: The DESIGN of the AWT and Swing packages in the JDK is based on composite patterns, providing users with a large number of Container artifacts (such as Containers) and member artifacts (such as Checkbox, Button, and TextComponent) within these boundaries. They all inherit and associate from the abstract Component class Component.

Decorators dynamically add additional responsibilities to an object and are more flexible than subclassing in terms of adding functionality. Scenario: Decorator mode is a way to dynamically add more functionality to existing functionality. When the system needs new functionality, it adds new code to an old class, often decorating the core responsibilities or major behaviors of the old class. The decorator pattern places each decorator function in a separate class and lets that class wrap the object it decorates. When special behavior needs to be performed, the client code can use the decorator function to wrap objects selectively and sequentially at run time.

Advantages: The decoration function in the class is moved out of the class, simplifying the original class. Effectively separate the core responsibility of the class from the decoration function and remove the repeated decoration logic in related classes.

Disadvantages: The use of the decorator pattern often results in a large number of small classes in the design, which can be confusing to programmers using this API.

Application: Java I/O is designed with decorator, and there are many classes in the JDK designed with decorator, such as Reader, Writer, OutputStream, etc.

A Facade provides a consistent interface for a set of interfaces in a subsystem that defines a high-level interface that makes the subsystem easier to use. Principle: perfect embodiment of the dependence inversion principle and Demeter’s law.

Scene:

A) Design stage: consciously separate the two different layers. B) Development phase: Add facade to provide a simple interface for the repetition and evolution of subclasses. C) During maintenance: Use the Facade class to provide a clear and simple interface to the legacy code so that the new system interacts with the facade and the facade interacts with the legacy code for all complex work.Copy the code

Advantages: 1. The use of the subsystem by the customer becomes simple, reducing the associated objects with the subsystem, and realizing the loose coupling relationship between the subsystem and the customer. It only provides a unified entrance to access subsystems, and does not affect users to directly use subsystem classes. 3. It reduces compilation dependence in large software systems and simplifies the process of system migration between different platforms.

Disadvantages: 1, the use of subsystem classes can not be well restricted, if the customer access to the subsystem class do too much restrictions will reduce variability and flexibility. 2, in the case of not introducing abstract facade class, adding a new subsystem may need to modify the facade class or client source code, violating the “open closed principle”.

The Flyweight pattern effectively supports a large number of fine-grained objects using sharing techniques. Scenario: If an application uses a large number of objects and the large number of objects causes a large storage overhead, you should consider using the free element pattern; In addition, most of the state of an object can be external. If the external state of an object is removed, many groups of objects can be replaced with relatively few shared objects. In this case, the shared element pattern can be considered.

Advantages: The meta schema avoids the overhead of a large number of very similar classes. In a program, a large number of fine-grained class instances represent data. If they are essentially the same except for a few arguments, moving them outside the class instance and passing them in during method calls can greatly reduce the number of single instances by sharing them.

Disadvantages: 1. The share pattern makes the application somewhat more complicated because it needs to distinguish between external and internal state. 2. In order for objects to be shareable, the share mode needs to externalize the state of the share object, and reading the external state makes the run time longer.

Apply: String class.

Proxy provides a Proxy for other objects to control access to that object. Principle: The proxy pattern introduces a degree of indirectness in accessing objects. (Demeter’s Law?)

Scene:

A) Remote proxy: Provides a local representation of an object in different address Spaces, thus hiding the fact that an object exists in different address Spaces. B) Virtual proxy: create expensive objects as needed, through which to store real objects that will take a long time to instantiate. C) Secure proxy: used to control access to real objects. D) Intelligence guidelines: The proxy handles something else when the real object is called. [Such as the number of references to the real object of the computer, the agent will attach some housekeeping when accessing an object to check whether the object is locked, whether it should be released, whether it should be loaded into memory, etc.]Copy the code

Advantages: 1) The proxy mode can separate the proxy object from the real called object, which reduces the coupling degree of the system to a certain extent.

2) The proxy mode plays an intermediary role between the client and the target object, which can protect the target object. Proxy objects can also perform other operations on target objects before they are called.Copy the code

Disadvantages: 1) Adding a proxy object to the client and the target will slow down the request processing.

2) Increased the complexity of the system.Copy the code

Application: The Proxy class and the InvocationHandler interface in the java.lang.Reflect package provide the ability to generate dynamic Proxy classes.

Publish/Subscribe: Defines a one-to-many dependency that allows multiple observers to listen on a subject object at the same time. The topic object notifies all observer objects when their state changes, allowing them to update themselves automatically. Scenario: Splitting a system into a series of cooperating classes has the disadvantage of maintaining consistency between related objects. Tight coupling makes maintenance and expansion difficult. The observer pattern is designed for decoupling, so that the relationship between one object and another becomes one where both sides depend on the abstract rather than on the concrete, so that changes in either side do not affect changes in the other.

Advantages: Decoupling.

Disadvantages: If there are loop dependencies between the observed, the observed will trigger loop calls between them, causing the system to crash. Pay special attention to this when using observer mode.

Application: Java.util. Observer, the Java class library implementation observes classes and interfaces of the Observer pattern.

The Template Method pattern defines the skeleton of the algorithm in an operation, deferring some steps to subclasses. Principle: Code reuse platform.

Scenario: Consider using the template approach pattern when you encounter a process consisting of a series of steps that are identical at a high level, but some of the steps may be implemented differently.

Advantages: The template method pattern implements its advantages by moving immutable behavior to the superclass, removing duplicate code from subclasses, providing a platform for code reuse, and helping subclasses get rid of repeated immutable behavior.

Disadvantages: If there are too many mutable base methods in the parent class, the number of classes will increase and the system will become larger.

AbstractClass AbstractClass TemplateMethod() is a TemplateMethod.

Command encapsulates a request as an object, allowing you to parameterize clients with different requests. Queue or log requests, and support undoable operations. Principles: Agile development principles

Scenario: Queue or log requests, and support actions such as undoable actions.

Advantages:

A) Command mode separates objects that request an operation from those that know how to perform it. B) It makes it easier to design a command queue. C) Commands can be easily logged if necessary. D) Allow the receiving party to decide whether to deny the request. E) It is easy to undo and redo requests. F) Adding a new concrete command class is easy because it does not affect other classes.Copy the code

Disadvantages: Increases the complexity of the system, by which I mean the number of classes.

Application:

1. Java. Util. The Timer class scheduleXXX () method (2) Java Concurrency Executor the execute () method (3) Java. Lang. Reflect. Methodinvoke () methodCopy the code

The State mode allows an object to change its behavior when its internal State changes, as if the object has changed its class. Principle: Single responsibility principle

Scenario: Consider using state patterns when an object’s behavior depends on its state and it must change its behavior based on state at runtime.

Advantages: The state mode mainly deals with situations where the conditional expression governing the state transition of an object is too complex. Complex decision logic can be simplified by moving the decision logic of states into a series of classes that represent different states. Eliminate large conditional branch statements.

Disadvantages: violates the open-closed principle

Application:

      1.  java.util.Iterator

      2. javax.faces.lifecycle.LifeCycle#execute()
Copy the code

The Chain of responsibility pattern avoids coupling between the sender and receiver of the request by giving multiple objects the opportunity to process the request. Chain the object and pass the request along the chain until an object processes it. Scenario: When a customer submits a request, the request is passed along the chain until an object is responsible for processing it.

Advantages: Because neither the receiver nor the sender has explicit information about the other, and the objects in the chain themselves do not know the chain structure, the result is that the chain of responsibility can simplify the interconnection of objects, which need to maintain only one reference to their successors, rather than all its candidate recipients. Developers can add or modify the structure of handling a request at any time, increasing the flexibility of assigning responsibilities to objects.

Disadvantages: A request will most likely not be processed at the end of the chain, or will not be processed because it is not configured correctly.

Given a language, define a representation of its grammar and define an Interpreter that uses that representation to interpret sentences in the language. Principle: Rely on the inversion principle

Scenario: If a particular type of problem occurs frequently enough, it may be worthwhile to represent individual instances of the problem as sentences in a simple statement. This allows you to build an interpreter that solves the problem by interpreting the sentences. The interpreter pattern is used when a language needs execution and you can represent sentences in the language as an abstract syntax tree.

Advantages: It is easy for the interpreter to change and extend the grammar, because the pattern uses classes to represent grammar rules, you can use inheritance to change or extend the grammar, and it is easier to implement the grammar. Because the implementation of the classes that define the nodes in the abstract syntax tree is broadly similar, they are easy to write directly.

Disadvantages: The interpreter pattern defines at least one class for each rule in the grammar, so a grammar with many rules can be difficult to manage and maintain, and other techniques (parser, compiler generator) are recommended when the grammar is very complex.

Application:

      1. java.util.Pattern

      2.  java.text.Normalizer

      3.  java.text.Format

      4.  javax.el.ELResolver
Copy the code

The Mediator pattern uses a mediation object to encapsulate a series of object interactions. Mediators make objects loosely coupled by eliminating the need to explicitly refer to each other, and can change their interactions independently. Scenarios: Generally used where a group of objects communicate in a well-defined but complex way, and where you want to customize a behavior that is distributed across multiple classes without generating too many subclasses. For example, Form forms, or ASPX pages.

Advantages:

A) Mediators reduce the coupling between abstract colleagues and make it possible to change and reuse classes independently. B) Because of the abstraction of how objects cooperate, the mediation is regarded as an independent concept and encapsulated in an object. In this way, the objects concerned are shifted from their own behaviors to their interactions, that is, to look at the system from a broader perspective.Copy the code

Disadvantages: Centralization of control leads to complexity for intermediaries.

Application:

      1.   java.util.Timer

      2.   java.util.concurrent.Executor#execute()

      3.   java.util.concurrent.ExecutorService#submit()

      4.   java.lang.reflect.Method#invoke()
Copy the code

Visitor pattern (Vistor) generator pattern :(the most complex pattern in GoF) represents an operation on elements in an object structure that allows you to define new operations on those elements without changing their classes. Scenario: Visitor pattern is suitable for stable data structure, but also easy to change algorithms. Visitor pattern is suitable for relatively stable data structure of the system, it decoupled the coupling between the data structure and the operation on the structure, so that the operation set can relatively free evolution. The purpose of the visitor pattern is to separate processing from data structures.

Advantages: Adding new operations is easy. The new action is the new visitor.

Disadvantages: It is difficult to add new data structures.

Application:

1. Javax.mail. Lang. Model. Element. 2 AnnotationValue and AnnotationValueVisitor javax.mail. Lang. Model. The element. The element and ElementVisitor 3. Javax.mail. Lang. Model. Type. TypeMirror and TypeVisitorCopy the code

A Strategy pattern defines a family of algorithms and encapsulates them so that they can be replaced with each other. This pattern makes changes to the algorithm not affect the users of the algorithm. Scenario: Policy patterns can be used to encapsulate not only algorithms, but almost rules of suture types. Different business logic can consider using policy patterns to handle changes.

Advantages: The policy classes of the policy pattern define a set of algorithms or behaviors that can be reused for context, and inheritance helps to extract common functionality from those algorithms. In addition, the policy pattern simplifies unit testing because each algorithm has its own class and can be tested separately through its own interface. When different behaviors pile up in a class, it’s hard to avoid using switch statements. But encapsulating these behaviors in a separate policy class eliminates conditional statements from classes that use these behaviors

Disadvantages: basic policy mode, options in the client, specific implementation to the policy mode context object. That’s not good. Using the policy pattern in conjunction with the factory class reduces the client’s responsibility. But it’s still not perfect, and using reflection is what makes you happy.

Application:

      1.   java.util.Comparator#compare()

      2.    javax.servlet.http.HttpServlet

      3.    javax.servlet.Filter#doFilter()
Copy the code

The Memento pattern captures the internal state of an object without breaking encapsulation and stores the state outside of the object so that the object can be restored to its original saved state later. Scenario: Memento encapsulates the details to be saved, suitable for a class whose function is responsible but needs to maintain or record the history of an attribute, or where the attribute to be saved is a small subset of many attributes.

Advantages: The memo pattern can be used to shield complex internal initiator information from other objects, thus preserving the boundaries of encapsulation appropriately.

Disadvantages: If the state of the sponsor role needs to be fully stored in the memo object, the memo object can be expensive in terms of resource consumption.

Application:

      1.   java.util.Date

      2.   java.io.Serializable
Copy the code

The Iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing the internal representation of the object. Scenario: When you need multiple ways to traverse an aggregation, consider using iterators.

Advantages: Iterator mode is to separate the traversal behavior of collection objects and abstract out an iterator, which can not only expose the internal structure of the collection, but also allow external code to transparently access the data inside the collection.

Disadvantages: Since the iterator pattern separates the responsibility of storing data and traversing data, adding new aggregation classes needs to correspond to adding new iterator classes, and the number of classes increases in pairs, which increases the complexity of the system to some extent.

Application: The collection container uses the iterator pattern

Reproduced in: www.cnblogs.com/DreamRecord…