23 Design patterns (concepts, principles, scenarios, advantages, disadvantages, applications) Brief introduction of the design mode

Source: Internet
Author: User
Tags extend generator shallow copy

There are 24 design patterns mentioned in the "Dahua Design Model":

Simple Factory mode, strategy mode, decoration mode, Agent mode, factory method mode, prototype mode, template method mode, appearance mode, builder mode, observer mode, abstract Factory mode, state mode, adapter mode, Memo mode, combination mode, iterator mode, single case mode, bridging mode, command mode, Responsibility chain mode, Mediator mode, enjoy meta mode, interpreter mode, visitor mode.

According to the type, can be divided into 3 categories:

1, the creation pattern : Abstract factory, builder model, factory method, prototype mode, single case mode;

The creation pattern abstracts the instantiation process. The creation pattern hides how instances of these classes are created and put together, and the whole system knows about these objects by the interfaces defined by the abstract class. In this way, the creation pattern provides flexibility in creating aspects of what, who created it, how she was created, and when it was created. Creating a corresponding number of prototypes and cloning them is usually more convenient than manually instantiating the class each time with the appropriate state.

2, structural mode : Adapter mode, bridging mode, combination mode, decorator mode, appearance mode , enjoy meta mode, Agent mode;

3. Behavioral Pattern : Observer mode, template method, command mode, State mode, responsibility chain mode, interpreter mode, mediator mode, visitor mode, policy pattern, Memo mode, iterator mode.

4, MVC mode : Set of observers, combination, strategy as a whole, is a combination of various modes of application, is a kind of architectural model.

Below according to "concept" + "principle" + "scene" + "advantage" + "disadvantage" + "application" to briefly describe 24 design patterns:

Abstract Factory Patterns (Abstracts Factory) provide an interface to create a series of related or interdependent objects without specifying their specific classes.

principle : LSP on the Richter replacement principle

Scenario : Create different product objects, the client should use a different specific factory.

Advantages :

A change to a specific factory can be done using different product configurations, making it easy to change a specific factory for an application.

b Let the concrete creation instance process and the client separate, the client through the abstract interface operation instance, the product specific class name also is separated by the concrete factory realization.

Disadvantages : If you want to add new methods, great changes.

Application :

A thecode to connect to the database in the JDK is a typical abstract factory pattern , with each database providing only one unified interface: Driver (Factory Class) and implementing the methods. Both JDBC and ODBC are able to extend the product line to connect to their own databases.

b The Java.util.Collection interface defines an abstract iterator () method, which is a factory method. Collection is an abstract factory for the iterator () method.

Builder Pattern (Builder) "also known as the generator pattern": separates a complex object's construction from its representation, allowing the same build process to create different representations.

principle : Relying on the reversal principle

Scenario : If you need to separate the build of a complex object from its representation, the same build process can create different representations. The builder pattern is the pattern that is applied when the algorithms that create complex objects should be independent of the components of the object and the way they are assembled.

advantages : Make the construction code separate from the presentation code.

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

Application : Append () method of StringBuilder and StringBuffer

The factory method pattern defines an interface for creating objects, so that subclasses decide which class to instantiate, and the factory method delays the instantiation of a class to its subclasses. Factory

principle : Open and closed principle

Scenario : Do not change the factory and product system, only to expand the product (change).

Advantages : It is a further abstraction and generalization of the simple factory model, which keeps the advantages of the Simple factory model (the factory class contains the necessary logical judgments, and dynamically instantiates the related classes according to the client's selection criteria). For the client, the dependency on the specific product is removed, and the shortcomings of the simple factory are overcome (the open closure principle is violated).

Disadvantage : Each additional product needs to be added to the class of a product factory, adding additional development. (Can be solved with reflection).

Application :

1. The iterator method in collection;

2. Java.lang.proxy#newproxyinstance ()

3. Java.lang.object#tostring ()

4. Java.lang.class#newinstance ()

5. Java.lang.reflect.array#newinstance ()

6. Java.lang.reflect.constructor#newinstance ()

7. java.lang.boolean#valueof (String)

8. Java.lang.class#forname ()

prototype mode (prototype) "name, Generator pattern": Specifies the type of object to create with a prototype instance, and creates a new object by copying the prototypes.

principle :

Scenario : Copying with clones when initialization information is not changed.

Benefits : Hides the details of object creation and greatly improves performance. Instead of reinitialize the object, it dynamically obtains the state of the object's runtime.

disadvantage : deep copy or shallow copy.

Application : The date class in the JDK.

 

 

The singleton mode (Singleton) guarantees that a class has only one instance and provides a global access point to access it.

principle : Encapsulation

scenario : Typically, we can have a global variable make an object accessible, but it doesn't prevent you from instantiating multiple objects, and one of the best ways to do that is to keep the class itself responsible for saving its unique instance. This class guarantees that no other instances can be created, and that it provides a way to access the instance.

Benefits : Controlled access to a unique instance.

disadvantage : a hungry man/lazy multithreaded simultaneous access may result in multiple instances.

application : Java.lang.Runtime GUI also has some (Java.awt.toolkit#getdefaulttoolkit () java.awt.desktop#getdesktop ())

Adapter Mode (Adapter) converts the interface of a class into another interface that the customer expects. The adapter mode makes it possible for those classes that could not work together because of incompatible interfaces.

In Gof design mode, adapters have two types, the class adapter pattern and the object adapter pattern.

A class adapter pattern: Multiple inheritance to match one interface to another, and C#,java languages do not support multiple inheritance, that is, a class has only one parent class.

b) Java generally refers to the object adapter pattern

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

Advantages : Can reuse existing classes, the client unified call the same interface, simpler, direct, compact.

Disadvantage : Adapter mode A little "mend" feeling, design phase to avoid use.

application : In the Java JDK, the adapter pattern uses many scenarios, such as java.util.arrays#aslist () in the collection package, Java.io.InputStreamReader in the IO package (inputstream), Java.io.OutputStreamWriter (OutputStream), etc.

Bridging Mode (bridge) separates the abstract part from its implementation, enabling them to change independently.

principle : synthesis/polymerization reuse principle

Scenario : The implementation system may have multiple angles of classification, each of which may change, then separate the multiple angles to allow them to change independently, reducing the coupling between them.

Advantages : Reduce the coupling of each part. Separation of abstraction and implementation parts, better scalability, can dynamically switch implementation, can reduce the number of subclasses.

Disadvantages : 1, the introduction of bridging mode will increase the system's understanding and design difficulty, because the aggregation association relationship is based on the abstraction layer, requires developers to design and programming for abstraction. 2, bridge mode requires the correct identification of the system of two independent changes in the dimensions, so its use of the scope has a certain limitations

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

Group Mode (composite) combines objects into a tree structure to represent a "partial-whole" hierarchy.

Scenario : When the requirements reflect part and whole hierarchies, and you want users to be able to ignore the differences between the grouped objects and the individual objects, you should consider using the combination mode when unifying all the objects in the composite structure.

Benefits : Combined mode allows customers to use composite structures and individual objects in a consistent way.

Disadvantages : Making the design more abstract, and if the object's business rules are complex, it is challenging to implement the combinatorial pattern, and not all methods are associated with the leaf object subclass.

application : The AWT and swing packages in JDK are designed to be based on a combination pattern that provides a large number of container artifacts (such as container) and member artifacts (such as CheckBox, Button, and textcomponent) to users in these boundary packs. They are all inherited, associated from the abstract component class component.

Decorative Mode (decorator) dynamically adds some additional responsibilities to an object, and in addition to adding functionality, the decorative pattern is more flexible than the build subclass.

Scenario : Decorative patterns are a way to add more functionality dynamically to existing features, and when the system needs new functionality, it adds new code to the old class, which usually decorates the core responsibility or main behavior of the original class. The decorated pattern puts each feature in a separate class, and allows the class to wrap the objects it wants to decorate, and when special behavior is required, the client code can wrap the object in the order that it needs to be decorated in a selective, sequential manner.

Advantages : Remove the decoration function from the class and simplify the original class. It is effective to separate the core responsibility of the class from the decoration function, and to remove the overlapping decoration logic in the related class.

disadvantage : Using the adorner pattern, often resulting in a large number of small classes in the design, too many, may cause the use of this API programmer's obsession.

application : Java I/o using decorative pattern design, jdk There are many classes are used in decorative mode design, such as: Reader class, writer class, OutputStream class.

The appearance pattern (façade) provides a consistent interface for a set of interfaces in a subsystem that defines a high-level interface that makes this subsystem easier to use.

principle : The perfect embodiment of the principle of dependency reversal and Dimitri law.

Scene :

A The design phase: the need to consciously separate two different layers.

(b) Development phase: Increasing appearance façade provides a simple interface that should repeat and evolve on a subclass.

c) During maintenance: Use the façade class to provide clear and simple interfaces for legacy code, allow new systems to interact with façade, and façade all the complex work of interacting with legacy code.

Advantages : 1, the use of the subsystem of the customer becomes simpler, reduces the associated object with the subsystem, and realizes the loose coupling relationship between the subsystem and the customer. 2, just provide a access subsystem of the unified portal, does not affect the user directly use Subsystem Class 3, reduce the large software system in the compiler dependency, and simplify the system in the process of porting between different platforms.

Disadvantages : 1, can not be very good to limit the use of the Subsystem class customers, if too many restrictions on customer access subsystem classes reduce variability and flexibility 2, without introducing abstract appearance classes, adding new subsystems may require modifying the appearance class or the source code of the client, violating the open and closed principle.

The use of shared technology (Flyweight) is an effective way to support a large number of fine-grained objects.

Scenario : If an application uses a large number of objects, and a large number of these objects cause a large storage overhead, you should consider using the usage pattern, and the object most States can be external states, if you delete the external state of the object, Then you can replace many groups of objects with relatively few shared objects, and you can consider using the pattern.

Advantage : The privilege mode avoids the overhead of a large number of very similar classes. In a program, a large number of fine-grained class instances represent data that, if they are essentially the same except for a few parameters, are transferred to the outside of the class instance and passed in at the method call, so that the number of individual instances can be drastically reduced by sharing.

Disadvantages : 1. The application is more complicated to some extent because of the need to distinguish between external state and internal state in the mode of privilege. 2. In order for the object to be shared, the pattern of the privilege requires the state of the object to be externalized, while reading the external state makes the running time grow longer.

Apply : String class.

proxy mode (proxy) provides a proxy for other objects to control access to this object.

principle : The proxy mode is to introduce a certain degree of indirection when accessing the object. (Dimitri Law.) )

Scene :

A remote proxy: Provides a local representation of an object in a different address space, which hides the fact that an object exists in a different address space. "WebService, clients can invoke agents to resolve remote access issues"

(b) Virtual proxies: Create expensive objects, as needed, to store the real objects for an instantiation that takes a long time. "Like a picture of an HTML Web page, the agent stores the path and size of the real picture."

c) Security agent: Used to control the access rights of real objects.

D Intelligent Guidance: When invoking real objects, the agent handles other things. "such as the number of references to a computer's real object, the agent appends some housekeeping to an object, checks whether the object is locked, whether it is released, whether it is loaded into memory, and so on."

Advantages : 1 The proxy mode can separate the proxy object from the object being called, and reduce the coupling degree of the system to some extent. 2 proxy mode plays a mediating role between client and target object, which can play a role in protecting target object. The proxy object can also perform other operations before the target object is invoked.

disadvantage : 1 Adding a proxy object to the client and target object can cause the request processing speed to slow down. 2 increases the complexity of the system.

Application : The proxy class and the Invocationhandler interface in the Java.lang.reflect package provide the ability to generate dynamic proxy classes.

Observer Mode (Publish/subscribe) "also known as publish-subscribe mode": Defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object simultaneously. The subject object notifies all observer objects when the state changes, allowing them to automatically update themselves.

Scenario : Splitting a system into a series of mutually collaborative classes has one drawback: the need to maintain consistency among related objects. Tight coupling can bring inconvenience to maintenance and expansion. The Observer model is born to understand coupling, so that the original object depends on the relationship of another object, become two parties are dependent on the abstraction, and no longer rely on the specific, so that their own changes will not affect the other side of the change.

advantages : Decoupling.

disadvantage : If there is a circular dependency between the observed, the observer triggers a circular call between them, causing the system to crash. It is important to pay special attention to this in the use of the Observer model.

application : Java.util.Observer, Java class Library implements classes and interfaces that observe (Observer) patterns.

The template method pattern (Template) defines the skeleton of an algorithm in an operation and delays some steps into subclasses.

principle : Code reuse platform.

Scenario : A process that is composed of a series of steps that needs to be performed, which is the same at a high level, but where the implementation of some of the steps may be different, the template method pattern needs to be considered at this time.

Advantage : The template method pattern is to remove the invariant behavior to the superclass, to eliminate duplicate code in subclasses to achieve its advantages, provides a code reuse platform, to help the subclass to get rid of the repetition of the invariant behavior of entanglement.

disadvantage : If there are too many basic methods in the parent class, the number of classes increases and the system becomes larger.

application : The Templatemethod () in the AbstractClass abstract class is the template method.

Command mode encapsulates a request into an object so that you can parameterize the client with different requests, queue or log request logs for requests, and support revocable operations.

principles : Agile Development Principles

scenario : Behavior such as queuing a request, logging a request log, and supporting an revocable operation.

Advantages :

A the command mode splits the object that requests an action from the object that knows how to perform an operation.

b It is easier to design a command queue.

(c) It is easier to log commands when needed.

d) Allow the party receiving the request to decide whether to veto the request.

E It is easy to implement the cancellation and redo of the request.

(f) It is easy to add new specific command classes because adding new specific command classes does not affect other classes.

Disadvantages : Increases the complexity of the system, where the complexity should mainly refer to the number of classes.

Application :

1. Schedulexxx () method in Java.util.Timer class

2. Java Concurrency Executor Execute () method

3. Java.lang.reflect.Methodinvoke () method

The state pattern , when the internal state of an object changes, allows the behavior to change, and the object looks like it has changed its class.

principle : Principle of single responsibility

Scenario : When an object's behavior depends on its state, and it must change its behavior according to its state at run time, consider using the state mode.

Advantage : The state pattern is mainly about situations where conditional expressions that control an object state transition are too complex. It is possible to simplify the complex judgment logic by transferring the judgment logic of State to a series of classes representing different states. "Eliminate large conditional branching statements."

disadvantage : Violating the open-closed principle

Application :

1. Java.util.Iterator

2. Javax.faces.lifecycle.lifecycle#execute ()

The responsibility chain pattern (chain of responsibility) gives multiple objects a chance to process the request, thus avoiding the coupling between the sender and the recipient of the request. Connect the object to a chain and pass the request along the chain until an object has processed it.

Scenario : When a customer submits a request, the request is passed along the chain until an object is responsible for handling it.

Advantage : The recipient and the sender do not have a clear message to each other, and the objects in the chain do not know the chain structure, the result is that the responsibility chain can simplify the mutual connection of objects, they only need to maintain a reference to the successor, and do not need to keep all of its candidate recipient references. developers can add or modify the structure of a request at any time, enhancing the flexibility to assign responsibilities to objects .

disadvantage : A request is most likely to go to the end of the chain is not processed, or because it is not properly configured without processing.

The interpreter pattern (interpreter) gives a language, defines a representation of its grammar, and defines an interpreter that uses the representation to interpret a sentence in a language.

principle : Relying on the reversal principle

Scenario : If a particular type of problem occurs on a high enough frequency, it may be worthwhile to express each instance of the problem as a sentence in a simple statement. This allows you to build an interpreter that interprets the sentences to solve the problem. You can use the interpreter pattern when a language needs to be executed, and you can represent the sentence in that language as an abstract syntax tree.

Advantage : The interpreter can easily change and extend the grammar, because the pattern uses classes to represent the grammar rules, and it is easier to implement grammars by using inheritance to change or extend the grammar. Because the implementations of the classes that define the nodes in the abstract syntax tree are generally similar, these classes are easy to write directly.

disadvantage : The interpreter pattern defines at least one class for each rule in the grammar, so the grammar containing many rules may be difficult to manage and maintain, and it is recommended that other techniques (parser, compiler Builder) be used when the grammar is very complex.

Application :

1. Java.util.Pattern

2. Java.text.Normalizer

3. Java.text.Format

4. Javax.el.ELResolver

The Mediator pattern (mediator) encapsulates a series of object interactions with a mediation object. Intermediaries make it loosely coupled and can independently change the interaction between objects without the need to display cross-references.

Scenario : A situation where a group of objects is generally used to communicate in well-defined but complex ways, and to customize a behavior that is distributed across multiple classes without having to generate too many subclasses. "For example, form form, or ASPX page."

Advantages :

A the abstract mediator class (mediator) reduces the coupling between abstract coworker classes (colleague), and can be independently altered and reused for various classes.

(b) As a result of the abstraction of how objects collaborate, the mediator is used as an independent concept and encapsulated in an object, so that the objects of concern are transferred from their own behavior to the interaction between them, that is, standing in a more macroscopic view of the system.

disadvantage : Centralization of control leads to the complication of intermediaries.

Application :

1. Java.util.Timer

2. Java.util.concurrent.executor#execute ()

3. Java.util.concurrent.executorservice#submit ()

4. Java.lang.reflect.method#invoke ()

Visitor Mode (vistor) generator pattern: (one of the most complex patterns in Gof) represents an operation that acts on the elements of an object structure, allowing you to define new operations that act on these elements without changing the classes of each element.

scene : The visitor pattern is suitable for stable data structure and easy to change algorithm "visitor pattern is applicable to the system with relatively stable data structure, which frees up the coupling between the structures and the operations acting on the structure, and is that the operation set can evolve relatively freely." The purpose of the visitor pattern is to separate the processing from the data structure.

Advantages : It's easy to add new operations. The new action is the new visitor.

disadvantage : It is difficult to add new data structures.

Application :

1. Javax.lang.model.element.AnnotationValue and Annotationvaluevisitor

2. Javax.lang.model.element.Element and Elementvisitor

3. Javax.lang.model.type.TypeMirror and Typevisitor

policy mode (strategy) it defines the algorithm family, encapsulates them separately, allowing them to replace each other, and this pattern allows the algorithm to change without affecting the user using the algorithm.

Scenario : The policy pattern can be used not only to encapsulate algorithms, but to encapsulate the rules of suture types, and different business logic can be considered to handle changes with a policy pattern.

Advantages : Policy classes define a series of reusable algorithms or behaviors for the context, and inheritance helps to extract the public functionality from these algorithms. In addition, the policy model simplifies unit testing because each algorithm has its own class that can be tested individually through its own interface. When different behaviors are stacked in a class, it is difficult to avoid using switch statements. However, by encapsulating these behaviors in a separate policy class, you can eliminate conditional statements in classes that use these behaviors

Disadvantages : The basic policy model, the choice of the right at the client, the implementation of the context to the policy mode of the object. It's not good. Using a combination of policy patterns and factory classes can reduce the client's responsibilities. But it is not perfect enough to be truly happy with reflection.

Application :

1. Java.util.comparator#compare ()

2. Javax.servlet.http.HttpServlet

3. Javax.servlet.filter#dofilter ()

The Memo mode (Memento) captures the internal state of an object without damaging the encapsulation, and saves the state outside the object, so that the object can later be restored to its previously saved state.

Scenario : Memento encapsulates the details to be saved, a class that is responsible for the function but needs to maintain or record the history of a property, or a property that needs to be saved is only a small part of many attributes.

Advantages : The use of Memo mode allows the complex initiator's internal information to be shielded from other objects so that the encapsulated boundaries can be properly maintained.

disadvantage : If the status of the initiator role needs to be stored completely in the memo object, the memo object will be expensive on resource consumption.

Application :

1. Java.util.Date

2. java.io.Serializable

The iterator pattern (iterator) provides a way to sequentially access each element of an aggregation object without exposing the internal representation of that object.

Scenario : You can consider using iterators when you need to iterate over multiple ways of aggregating.

Advantages : The iterator pattern is to separate the traversal behavior of the collection object, abstract an iterator to be responsible, so that the internal structure of the collection can not be exposed, but also allow the external code to transparently access the data within the collection.

disadvantage : Because the iterator pattern separates the responsibilities of storing data and traversing data, adding new aggregation classes requires corresponding additions to the new iterator class, and the number of classes increases to a certain extent, adding to the complexity of the system.

Application : The collection container uses an iterator pattern

Application of design Patterns in JDK: http://blog.csdn.net/u013782203/article/details/52214393

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.