Design Pattern Summary

Source: Internet
Author: User

Original source: Chenssy

From July onwards until the end of September to read the design mode, in the process I dare not say I have mastered the contents of the book, or 1/5, not able to say also not qualified to say. But the result is not important, the important is this process my harvest! Mainly include the following aspects:

1. I have known so many design patterns. Just touch Java not long in the seniors there have heard the design model name, but because of limited capacity, has been afraid to touch. Now I have the honor to know all of them.

2, began to have the theory of design. In contact with the design mode before not how to think about the design aspects, see the problem immediately hands-on solution, did not think how to design better, how to be this piece more optimized, beautiful.

3, began to consider the scalability of the system.

4, after encountering the problem began to want to have that design pattern will apply this scene.

5, the object-oriented has a deeper understanding.

My talent is not intelligent, not smart, not the kind of genius, all the Insight Limited!!! Too much gossip, look at the following two pictures

The relationship between design patterns:

General overview of Design Patterns:

I. Design principle 1, single duty principle

A class, and only one causes it to change. There should be only one duty. Each responsibility is an axis of change, and if a class has more than one responsibility, these responsibilities are coupled together. This can lead to fragile designs. When a duty changes, other responsibilities may be affected. In addition, multiple responsibilities are coupled together, which can affect reusability. For example, to achieve separation of logic and interface. From: Baidu Encyclopedia

2. Opening and closing principle (Open Close Principle)

The open and closed principle is to say to the expansion opening, to modify the closure . When the program needs to expand, can not modify the original code, to achieve a hot plug effect. So a nutshell is: In order to make the program good extensibility, easy to maintain and upgrade. To achieve this, we need to use interfaces and abstract classes, which we will refer to later in the specific design.

3. The principle of substitution on the Richter scale (Liskov Substitution Principle)

One of the fundamental principles of object-oriented design of the Richter substitution principle (Liskov Substitution Principle LSP). The Richter substitution principle says that where any base class can appear, subclasses must be able to appear. LSP is the cornerstone of inheritance reuse, only if the derived class can replace the base class, the function of the Software unit is not affected, the base class can be really reused, and the derived class can also add new behavior on the basis of the base class. The principle of substitution on the Richter scale is a supplement to the principle of "open-closed". The key step in implementing the "open-close" principle is abstraction. The inheritance of the base class and subclass is the concrete implementation of abstraction, so the principle of the substitution of the Richter scale is the specification of the concrete steps to realize the abstraction. From: Baidu Encyclopedia

4. Dependence reversal principle (dependence inversion Principle)

The so-called dependency inversion principle (dependence inversion Principle) is to rely on abstraction and not rely on specifics. Simply put, it requires programming the abstraction, not programming the implementation, which reduces the coupling between the customer and the implementation module.

The key to realize the open and close principle is abstraction, and from abstract to materialize realization, if the principle of opening up is object-oriented design, then the dependency reversal principle is the main means of object-oriented design. From: Baidu Encyclopedia

5. Interface Isolation principle (Interface segregation Principle)

This principle means that using multiple isolated interfaces is better than using a single interface. or a reduction of the coupling between the class meaning, from here we see, in fact, the design pattern is a software design ideas, from the large software architecture, in order to upgrade and maintenance convenience. So there are multiple occurrences: reducing dependency and reducing coupling.

6. Synthetic multiplexing principles (Composite reuse Principle)

The principle of synthetic reuse is to use some existing objects in a new object through association relationships (including combinatorial relationships and aggregation relationships) to make them part of new objects; The new object is used to re-use its existing functions by delegating methods that call existing objects. In short: Use the combination/aggregation relationship as much as possible, with less inheritance.

7, Dimitri Law (least known principle) (Demeter Principle)

Why is it called the least known principle, that is to say: an entity should be as small as possible interaction with other entities, so that the system function module is relatively independent. This means that a software entity should interact with as few interactions as possible with other entities. Thus, when a module is modified, it will minimize the impact of the other modules, the extension will be relatively easy, this is the software entity communication between the restrictions, it requires limiting the width and depth of communication between software entities.

Second, create a model

In software engineering, the creation pattern is a design pattern that deals with object creation and attempts to create objects in the right way, depending on the actual situation. Basic object creation can lead to design problems or increase the complexity of the design. The Create pattern solves the problem by controlling the creation of the object in some way.

The creation pattern is composed of two dominant ideas. One is to encapsulate the specific classes used by the system, and to hide the ways in which instances of these concrete classes are created and combined.

The creation pattern is divided into object-creating mode and class-creating mode. Object-creation mode handles the creation of objects, class-created pattern-processing classes. In detail, the object creation pattern defers part of the object creation to another object, while the class-creation pattern defers the creation of its object to the subclass.

1. Abstract Factory mode (Factory)

The so-called abstract factory pattern is that she provides an interface for creating a family of related or dependent objects without explicitly specifying a specific class. He allows clients to use an abstract interface to create a set of related products without the need for a specific product that relates to the actual output. In this way, customers can be decoupled from specific products. It has the advantage of isolating the build of a specific class so that the client does not need to know what is being created, and the disadvantage is that adding new behavior can be cumbersome, because when you add a new product object, you need to change the interface and all of its sub-classes. The UML structure diagram is as follows:

Participants:

Abstractfactory: Abstract Factory. An abstract factory defines an interface that all specific factories must implement, and this interface contains a set of methods for producing products.

Concretefactory: Specific factory. Specific factories are used to produce different product families. To create a product, customers only need to use one of the plants without having to instantiate any product objects at all.

Abstractproduct: Abstract products. This is a family of products, each of which can produce a whole group of products.

Product: Specific products.

2. Builder mode

For the builder pattern, it separates the construction and presentation of a complex object, allowing the same build process to create different representations. The internal structure that applies to those product objects is more complex.

The builder model encapsulates the construction process of complex products in different ways, making the creation process very clear, allowing us to more precisely control the creation of complex product objects, while isolating the creation and use of complex product objects, enabling the same creation process to create different products. However, if the internal structure of a product is too complex, it will cause the whole system to become very large, not conducive to control, and if there are a large number of product differences between the builder model is not applicable, after all, the world there are two of the same point large products are not many, so it has limited use range. Its UML structure diagram:

Participants:

Builder: Abstract builder. It declares an abstract interface that is specified for each part of the product object that is created.
ConcreteBuilder: Concrete Builders. Implement abstract interfaces to build and assemble individual parts.
Director: Conductor. Build an object that uses the builder interface. It is mainly used to create a complex object, it has two functions, one is: to isolate the customer and the object of the production process, and the other is responsible for controlling the production process of product objects.
Product: Production role. A specific Product object.

3. Factory method Mode (Factory methods)

As the twin brother of the abstract factory model, the factory method pattern defines an interface to create an object, but subclasses decide which class to instantiate, which means that the factory method pattern defers instantiation to the subclass.

Factory method mode is very consistent with the "open and close principle", when the need to add a new product, we only need to add a specific product class and corresponding to the specific factory can be, no need to modify the original system. At the same time in the factory method mode users only need to know the production of the specific factory, no relationship to the product creation process, even the specific product class name do not need to know. Although he is well in line with the "open and close principle", but because each new new product will need to add two classes, which will inevitably lead to the complexity of the system increase. Its UML structure diagram:

Participants:

Product: Abstract products. All products must implement this common interface, so that the classes that use these products can reference this interface. Rather than specific classes.

Concreteproduct: Specific products.

Creator: Abstract Factory. It implements all methods of manipulating the product, but does not implement a factory method. Creator all subclasses must implement the FactoryMethod () method.

Concretecreator: Specific factory. The actual factory where the products are manufactured. It is responsible for creating one or more specific products, and only the Concretecreator class knows how to create those products.

4. Prototype mode (PROTOTYPE)

In our application there may be some object structure is more complex, but we need to use them frequently, if this time we will continue to build this object is bound to greatly reduce the system memory, this time we need to use the prototype pattern to the complex and frequently used object cloning. So the prototype pattern is to use the prototype instance to specify the kind of object to create and create a new object by copying the prototypes.

It is primarily applied when the cost of creating new objects is too high. Its main advantage is that it simplifies the creation of new objects, improves efficiency, and provides a simplified creation structure in prototype mode. UML Structure diagram:

Participants:

Prototype: Abstract Prototype class. Declares the interface of the clone itself.
Concreteprototype: Concrete Prototype class. Implements the specific operation of the clone.
Client: Customer class. Let a prototype clone itself, thereby acquiring a new object.

5. Single case mode (Singleton)

The singleton pattern, literally, is the meaning of an instance. So it is defined as ensuring that a class has only one instance and provides a global access point.

The singleton mode has the following features:

1, only one instance.

2, can self-instantiate.

3, provide the global access point.

So when you need only one instance object in the system, or only one public access point in the system, you can use Singleton mode in addition to this public access point when you cannot access the instance through another access point.

The main advantage of the singleton mode is to save the system resources, improve the system efficiency, and also can strictly control the customer's access to it. Perhaps because there is only one instance of the system, which leads to the overload of the single-case class, violates the "single responsibility Principle", and there is no abstract class, so it is difficult to expand. Its UML structure diagram is very simple and has only one class:

Participants:

Singleton: Single case.

Three, structural model

Structure pattern is mainly used to deal with the combination of class or object, it describes how to better combine the class or object, it is from the structure of the program to solve the problem of coupling between the modules. It mainly includes adapter mode, bridge mode, combination mode, decoration mode, appearance mode, enjoy meta mode, proxy mode, this seven mode.

1. Adapter mode (Adapter)

In our application we may need to communicate the classes of two different interfaces, without modifying the two, we may need a middleware to complete the process of convergence. This middleware is the adapter. The so-called adapter pattern is to convert the interface of a class into another interface that the customer expects. It allows the original two incompatible interfaces to seamlessly complete the docking.

As a middleware adapter, the target class and the adaptation are decoupled, which increases the transparency and reusability of the classes.

Participants:

Target: Object abstract class.

Adapter: Adapter class. The source interface is transferred to the target interface by wrapping a adaptee inside.

Adaptee: Adapter class. A class that needs to be adapted.

Client: Customer class.

2. Bridging mode (bridge)

If a system can be categorized from multiple angles, and each classification is likely to change, then what we need to do is to separate the various angles so that they can change independently and reduce the coupling between them, and this separation process uses bridging mode. The so-called bridging pattern is the separation of the abstraction and implementation, allowing them to change independently.

Bridging mode transforms inheritance relationships into associative relationships, encapsulates changes, completes understanding decoupling, reduces the number of classes in the system, and reduces the amount of code.

Participants

Abstraction: abstract class.
Refinedabstraction: Expands the abstract class.
Implementor: Implements the class interface.
Concreteimplementor: Concrete implementation class.

3. Combination mode (Composite)

Combined patterns combine multiple objects to form a tree structure to represent the structural hierarchy of "whole-part". It defines how the container object and the leaf object can be combined recursively, so that the customer does not need to distinguish between the use of the process, and they may be treated in a consistent way.

One thing to be aware of in the use of combinatorial mode is that the combination pattern is the most critical: the Leaf object and the combined object implement the same interface. This is why the combination pattern can handle leaf nodes and object nodes uniformly.

Although the combination mode can clearly define the hierarchical complex objects, but also makes it easier to add new artifacts, this leads to a more abstract design of the system, and if the business rules of the system are more complex, the use of combinatorial patterns has some challenges.

Participants:

Component: An object declaration interface in a combination that implements the default behavior for all classes of common interfaces, where appropriate. Declares an interface for accessing and managing component subassemblies.
Leaf: the Leaf object. Leaf nodes have no sub-nodes.
Composite: A container object that defines the behavior of a minor point, which is used to store subassemblies, and to implement operations related to subassemblies in the component interface, such as add (add) and delete (remove).

4. Decorator Mode (Decorator)

We can add behavior to an object through inheritance and composition, although using inheritance can well have the behavior of the parent class, but it has several drawbacks: first, the complex relationship between objects, the system becomes complex and is not conducive to maintenance. Second, easy to produce "class explosion" phenomenon. Third, is static. Here we can solve this problem by using decorator mode.

Decorator mode, which dynamically attaches responsibility to the object. To extend functionality, decorators provide a more resilient alternative than inheritance. Although the decorator pattern can dynamically attach responsibility to the object, he produces many small objects that increase the complexity of the system.

Participants:

Component: Abstract artifacts. is to define an object interface that can dynamically add responsibilities to these objects.

Concretecomponent: Concrete components. is to define a specific object, or to add some responsibility to the object.

Decorator: Abstract Decorative class. is to decorate the abstract class, inherit the component, from the outer class to extend the function of the component class, but for component, there is no need to know decorator exist.

Concretedecorator: The specific adornment class, plays the function which adds the responsibility to the component.

5. Appearance mode (facade)

We all know that the lower the coupling between classes and classes, the better the reusability, if two classes do not have to communicate with each other, then do not let the two classes have a direct correlation, if you need to call the inside of the method, you can forward the call through a third party. The appearance pattern is a very good interpretation of this passage. The appearance mode provides a unified interface for accessing a group of interfaces in a subsystem. It minimizes the interdependencies between subsystems in an application, and it provides a simple, single barrier to the subsystem through which the customer communicates with the subsystem.

By using the appearance mode, the client's reference to the subsystem is made simple and the loose coupling between the customer and the subsystem is realized. However, it violates the "open and close principle" because adding a new subsystem may require modifying the source code of the skin class or client.

Participants:

Facade: Appearance role. Know which subsystem classes are responsible for processing the request, and the client's request is proxied to the appropriate subsystem for processing.

SubSystem: Subsystem role. Implement subsystem functions to handle requests sent by Facade objects.

6. Enjoy meta-mode (Flyweight)

Objects in a system can consume too much memory, especially those that are heavily duplicated, which is a huge waste of system resources. The enjoy meta-mode provides a solution for reuse of objects using shared technologies that reuse the same or similar objects.

The enjoy meta-mode is that running sharing technology effectively supports the reuse of a large number of fine-grained objects. The system uses a small number of objects, and these are more similar, the state changes small, you can achieve multiple reuse of objects. One thing to note here: The enjoy meta mode requires that objects that can be shared must be fine-grained objects.

Enjoy meta-mode through sharing technology so that the number of objects in the system is greatly reduced, while the use of meta-mode using the internal state and external state, while the external state is relatively independent, does not affect the internal state, so the enjoyment of meta-objects in different environments can be shared. At the same time it is divided into the internal state and the external state, the enjoyment of meta-mode will make the system more complex, but also cause the reading of external state takes too long.

Participants:

Flyweight: Abstract enjoy meta class. The superclass or interface of all the specific classes of flyweight, through which the interface can accept and act on external topics.
Concreteflyweight: The specific share of the meta-class. Specifies the internal state to increase storage space for the internal state.
Unsharedconcreteflyweight: Non-shared-specific class of privileges. Indicates those flyweight subclasses that do not need to be shared.
Flyweightfactory: Enjoy the Meta factory class. Used to create and manage flyweight objects, which are primarily used to ensure that flyweight is reasonably shared, and when a user requests a flyweight, Flyweightfactory provides a flyweight object that has already been created or creates a new one if it does not exist.

7, Agent mode (proxy),

The proxy mode is to provide a proxy for an object, and the proxy object controls the reference to the original object. It makes it impossible for customers to communicate directly with real target objects. The proxy object is the representative of the target object, and the other operations that need to deal with this target object are in negotiations with the proxy object.

A proxy object can act as an intermediary between the client and the target object, thus playing a role in protecting the target object and, at the same time, reducing the coupling of the system to a certain extent.

Participants:

Subject: Abstract role. Declares a common interface between a real object and a proxy object.

Proxy: Agent role. The proxy object implements the same interface as the real object, so it can proxy real objects at any moment. The proxy role contains a reference to the real object, so she can manipulate the real object, as well as attach other actions, which are equivalent to encapsulating the real object.

Realsubject: Real characters. It represents the real object and is the object we will eventually refer to.

Iv. Behavioral Patterns

Behavioral patterns are primarily used to describe how classes or objects interact and assign responsibilities. It involves the allocation of responsibilities between algorithms and objects, not only describing the patterns of objects or classes, but also describing the way they communicate, which shifts your attention from the control flow to the relationship between objects. The Behavioral class pattern uses the inheritance mechanism to dispatch behavior between classes, while the behavioral object pattern uses objects to compound rather than inherit. It mainly includes how to design patterns in 11: Responsibility chain mode, command mode, interpreter mode, iterator mode, mediator mode, Memo mode, observer pattern, State mode, policy mode, template method mode, visitor mode.

1. Responsibility chain mode (Chain of Responsibility)

The responsibility chain pattern describes how requests are passed along the chain of objects. It makes a chain of objects, and the sender sends the request to the first recipient of the chain, and passes along the chain until there is an object to process it or until finally there is no object processing and remains at the end of the chain.

Avoid the request sender to be coupled with the receiver, so that multiple objects are likely to receive requests, connect these objects into a chain, and pass the request along this chain, until there is an object to handle it, this is the responsibility chain mode. In the responsibility chain mode, each object is possible to process the request, thus enabling decoupling between the sender and receiver of the request. At the same time, the chain of responsibility mode simplifies the structure of the object, so that each object only needs to refer to its successor, without having to understand the whole chain, which improves the system flexibility and makes it easier to add new request processing classes. However, in the chain of responsibility, we cannot guarantee that all requests can be processed and that it is not conducive to observing runtime features.

Participants:

Handler: Abstract processor. Defines a method for processing a request. All handlers must implement the abstract class.
Concretehandler: Specific processor. Handle the request it is responsible for, and can also access its successors. If it is able to process the request, it is processed, otherwise the request is passed to its successor.
Client: Customer class.

2. Command mode

There are times when we want to send a request to an object, but we don't know who the specific recipient of the request is, and how the specific process is done, and we know that the specific request recipient is specified in the program's run, which we call the command pattern for encapsulating the request as an object. So the command pattern encapsulates the request into objects so that different requests, queues, or logs can be used to parameterize other objects. Also, the command mode supports the revocable operation.

The command pattern can be fully decoupled between the sender and receiver of the request, there is no direct connection between the sender and the receiver, the sender only needs to know how to send the request command, the rest can be completely regardless, even if the command is not the success of care. At the same time, we can easily add new commands, but it may be because of the convenience and the encapsulation of the request will lead to an excessive number of specific command classes in the system.

Participants:

Command: Abstract Commands class. The interface used to declare the execution of an operation.

Concretecommand: the specific command class. Binds a recipient object to an action, invoking the corresponding action of the receiver to implement Excute.

Invoker: Caller. This command is required to execute the request.

Receiver: Receiver. Knowing how to implement the actions associated with executing a request, any class is likely to be a recipient.

Client: Customer class.

3. Interpreter mode (interpreter)

The so-called interpreter pattern is the grammar of the definition language, and an interpreter is created to interpret the sentences in that language. The interpreter pattern describes how to make up a simple language interpreter, mainly used in compilers developed using object-oriented languages. It describes how to define a grammar for a simple language, how to represent a sentence in that language, and how to interpret these sentences.

Participants:

Abstractexpression: An abstract expression. Declares an abstract interpretation operation that is shared by all nodes in the abstract syntax tree.

Terminalexpression: an terminator expression. Implements interpretation operations related to Terminator in the grammar. Implements the method required in an abstract expression. Every terminator in grammar has a specific ending expression corresponding to it.

Nonterminalexpression: Non-terminator expression. A non-terminator-related interpretation operation in the grammar.

Context: Environment class. Contains some global information outside of the interpreter.

Client: Customer class.

4. Iterator mode (Iterator)

For iterations we often use in the programming process, can walk in the aggregation of each element, but also can provide a number of different traversal methods, this is the design of the iterator mode motivation. In our actual development process, we might need to traverse the whole object in different ways depending on the requirements, but we don't want to be flooded with different traversal operations in the abstract interface of the aggregate object, so we want something that can traverse an aggregate object in many different ways, The iterator pattern appears.

What is the iterator pattern? The so-called iterator pattern is to provide a way to sequentially access individual elements in an aggregated object, rather than exposing their internal representations. The iterator pattern is to pass the responsibility of the iterative element to the iterator, not to the aggregation object, and we can implement an iteration of the aggregate object even without knowing the internal structure of the aggregate object.

With the iterator pattern, the structure of the aggregation object is simpler, it does not need to focus on the traversal of its elements, it only needs to focus on what it should focus on, which is more in line with the principle of single responsibility.


Participants:

Iterator: Abstract iterator: An interface that all iterators need to implement, providing a way between the elements of the walk aggregation object.

Concreteiterator: the specific iterator. This specific iterator enables the traversal of specific aggregated objects. Each aggregation object should correspond to a specific iterator.

Aggregate: Abstract Aggregation class.

Concreteaggregate: The specific aggregation class. Implements the Creatoriterator () method, which returns an iterator to the aggregation object.

5. Intermediary mode (mediator)

Rent the experience you have had! In this process, the intermediary structure plays a very important role, it is here to play a role in the middle, to us and the landlord to pass information to each other. In the outside world of software, such a middle person is also needed. In our system sometimes there is a strong, complex relationship between objects and objects, if they have a direct connection between them, it will inevitably lead to the whole system becomes very complex, and scalability is poor! Before we knew that if two classes did not have to communicate with each other, we should not let them have a direct correlation, if it is necessary to communicate, we can forward their request through a third party. Again, here we use intermediaries to solve this problem.

The so-called mediator pattern is the use of a mediation object to encapsulate a series of object interactions, the mediator makes the objects do not need to explicitly reference each other, so that they are loosely coupled, and can independently change their interaction. In the mediator mode, the mediation object is used to encapsulate the relationship between objects, and each object can communicate with each other without needing to know the specific information through the Mediator object. It reduces the inter-relationship between objects, provides system reusability, and simplifies the structure of the system.

In the mediator mode, each object does not need to know each other, they only need to know the Mediator object, but the intermediary object must know all the objects and their relationship, it is because this led to the structure of the intermediary object is too complex, assume too much responsibility, At the same time it is the core of the whole system, and its problems will lead to the problem of the whole system. So if there is a "many-to-many" complex relationship group in the design process of the system, do not rush to use the intermediary mode, but think carefully whether you design the system has problems.

Participants:

Mediator: Abstract Mediator. Defines the interface between a colleague object and a mediator object.

Concretemediator: Specific intermediaries. The way to implement an abstract mediator is to know all of the specific colleague classes, and to receive information from a specific colleague class, and to send information to a specific colleague class.

Colleague: Abstract colleague class.

Concretecolleague: Specific colleague class. Each specific colleague class needs to know its own behavior, but they all need to know the broker.

6. Memo Mode (Memento)

Regret medicine everyone wants, but the fact is cruel, there is no regret medicine can buy, but also not only so, in the software world there is regret medicine! Memo mode is a kind of regret medicine, it gives our software the mechanism of regret medicine, through which it can bring the system back to a specific historical state.

The so-called memo pattern is to capture the internal state of an object without destroying the package, and to save the state outside of the object, so that the object can be restored to its previously saved state at a later time. It enables the encapsulation of information so that customers do not need to care about the details of state preservation. Saving will consume resources, so the drawback of memo mode is to consume resources. If the class has too many member variables, it is bound to occupy a larger resource, and each time the save consumes a certain amount of memory.

Participants:

Originator: the original generator. is responsible for creating a memo that records the internal state of the current object, which can also be used to restore the internal state using the memo. At the same time, the original generator can also decide the internal state of memento storage originator as needed.

Memento: Memo. Used to store the internal state of the originator, and can prevent objects other than originator from accessing the memento. There are two interfaces in memo memento, where caretaker can only see the narrow interface in the memo, and it can only pass the memo to other objects. Originator can see a wide interface, allowing it to access all data returned to its previous state.

Caretaker: the person in charge. Be responsible for saving memos, not manipulating and accessing the contents of the memo, but only passing notes to other objects.

7. Observer mode (OBSERVER)

What is the Observer pattern? The Observer pattern defines a one-to-many dependency between objects, so that when an object changes state, all its dependents are notified and updated automatically.

Here, the object of change is called the observation target, and the object being notified is called the Observer. An observation target can correspond to multiple observers, and these observers are not interconnected, so you can add and remove observers as needed, making the system easier to scale.

So the Observer provides an object design that allows a loosely coupled approach between the subject and the observer.

Participants:

Subject: Target. He kept all the references to the viewer in a gathering, and each subject could have multiple observers.

Observer: The Observer. Define an interface for all specific observers to update themselves in a timely manner when the topic is notified.

ConcreteSubject: Specific topics. The state is stored in the specific observer object. Notify all observers when changes are made to the specific subject.

CONCRETEOBSERVER: Specific observer. Implements the update interface required by the abstract observer role in order to reconcile the state of itself with the subject state.

8. Status mode (state)

In many cases, the behavior of our object depends on one or more of its changing properties, which we call state, that is, the behavior-dependent state, that is, when the object causes his state to change because of its interaction with the outside, and its behavior changes accordingly. In this case, we can not use the behavior to control the change of state, but should stand in the state of the angle to think about the behavior, that is, what kind of state is to be done what behavior. This is the state pattern.

So the state pattern is to allow the object to change its behavior when the internal state changes, and the object looks as if it had modified its class.

In the state mode we can reduce large chunks of if...else statements, which are allowed to state the transformation logic and Status object synthesis, but the cost of reducing the IF...ELSE statement is to exchange a large number of classes, so the state pattern is bound to increase the number of classes or objects in the system.

At the same time, the state mode is to put all the behaviors related to a state into a class, and can easily add new state, only need to change the state of the object to change the behavior of the object. However, this will lead to the structure and implementation of the system will be more complex, if improper use will lead to the structure of the program and code confusion, not conducive to maintenance.

Participants:

Context: Environment class. Can include some internal states.
State: Abstract status class. State defines a common interface for all States, and any State implements the same interface, so that states can be converted to each other.
Concretestate: The specific State class. The state class is used to process requests from the context, and each concretestate provides its own implementation of the request, so the behavior changes when the context changes state.

9. Strategy Mode (strategy)

We know that there may be many ways to achieve it, but there is always one of the most efficient way to do it in the software development world, and there are many ways to implement a function, but we need a simple and efficient way to implement it, so that the system can be very flexible, this is the strategy mode.

So the strategy pattern is to define the algorithm family, separately encapsulated, so that they can be converted to each other, this mode of the algorithm is independent of the client using the algorithm.

In the strategy mode it defines these problem-solving methods as an algorithm group, each of which corresponds to a specific algorithm, and here's an algorithm I call a strategy. Although the strategy pattern defines the algorithm, it does not provide the choice of the algorithm, that is, what the algorithm is most appropriate for the problem is not the policy mode of concern, so the choice of policy is for the client to do. Customers must be aware of the difference between each algorithm and when and where to use what strategy is the most appropriate, thus increasing the burden on the client.

At the same time, the strategy model also perfectly conforms to the "open and close principle", the user can choose the algorithm or the behavior on the basis of not modifying the original system, also can add the new algorithm or the behavior flexibly. However, a policy corresponding to a class will be the system produces a lot of policy classes.

Participants:

Context: Environment class. Maintains a reference to a strategy object, configured with a concretestrategy, to define an interface to allow strategy to access its data.
Strategy: Abstract policy class. Defines the public interface for all supported algorithms. The context uses this interface to invoke an algorithm defined by a concretestrategy.
Concretestrategy: Specific policy class. Encapsulates the implementation of a specific algorithm.

10. Template Method Mode

Sometimes we do a few things the same steps, only a little bit different, in the software development of the world is the same, if we all do all these steps, time and effort not to please. So we can take these steps to decompose, encapsulate, and then inherit the way to inherit can, of course, different can rewrite their own implementation! This is the solution provided by the template method pattern.

The so-called template method pattern is the skeleton of an algorithm defined in a method, and some steps are deferred to subclasses. The template method allows subclasses to redefine some of the steps in the algorithm without changing the structure of the algorithm.

The template method pattern is based on the inherited code reuse technique. In the template method pattern, we can put the same part of the code in the parent class, and put different code into different subclasses. In other words, we need to declare an abstract parent class, implement some of the logic in the form of concrete methods and concrete constructors, and then declare some abstract methods that allow subclasses to implement the remaining logic, and different subclasses can implement the logic in different ways. So template method template is actually a common method, but this method is the algorithm implementation of the steps encapsulated.

Participants:

AbstractClass: abstract class. Implement a template to implement the basic skeleton of the algorithm, the specific subclass will redefine the Primitiveoperation () method to implement an algorithm step.

Concreteclass: Specific subclasses. Implement the Primitiveoperation () method to complete the steps associated with a particular subclass in the algorithm.

11. Visitor Mode (Visitor)

The visitor pattern is commonly known as the hardest of 23 design patterns. In addition to the complex structure, understanding is more difficult. In our software development we may have different processing of the same object, if we do separate processing, will have a catastrophic error. For this kind of problem, the visitor pattern provides a better solution.

The visitor pattern represents an operation that acts on elements in an object's structure, allowing us to define new actions that act on these elements without changing the class of each element.

The purpose of the visitor pattern is to encapsulate some operations that are applied to a data structure element, and once those operations need to be modified, the data structure that accepts the operation can remain intact. Provides multiple access operations for different types of elements, and adds new ways to operate without modifying the original system. At the same time, we need to make it clear that the visitor pattern is suitable for those data structures that are relatively stable, because he separates the operation of the data from the data structure, if a system's data structures are relatively stable, but the operation algorithm is easy to change, it is more suitable for the applicable visitor pattern, Because the visitor pattern makes the arithmetic operation more simple.

Participants:

Vistor: Abstract visitor. An operation declared for each class of concreteelement in the object structure.
Concretevisitor: Specific visitors. Implement the visitor declaration for each operation that is part of the implementation algorithm for each operation.
element: An abstract element. Defines an accept operation that takes a visitor as a parameter.
Concreteelement: Concrete elements. Implement the accept operation.
Objectstructure: Object structure. The ability to enumerate its elements can provide a high-level interface to allow visitors to access its elements.

Design Pattern Summary

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.