Lying design pattern ---- summarized various modes

Cheng Jie lying design patterns explain the wonders of design patterns in the form of the novel, is a book for beginners to get started fast.

By encapsulation, inheritance, polymorphism, to reduce the coupling procedure. With a design pattern is the rational use of these three methods make the program more flexible, easy to modify and easy to reuse.

Copy vs junior programmers reuse work is ctrl + c and ctrl + v, when the code is more to a certain extent when maintenance becomes a disaster. One of the principles is to avoid duplication of programming.

Polymerization and has a synthetic polymeric represent a weak relationship reflects a target object can contain b, b but the object is not a part of the object. Synthesis has a strong relationship, reflecting the strict relationship between parts and the whole, the parts and the whole life cycle of the same.


Abstract class is a collection of object-oriented programming, better than a class, the class division is to package, but the classification is based on the abstract, having the same properties and functions of the object.
Strategy Mode (strategy) Strategy pattern defined family of algorithms, encapsulate them, so that they can replace each other, so that the algorithm change does not affect customers using the algorithm.
Strategy Mode is a way to define a series of algorithms, algorithms encountered completion of the work is the same, but to achieve different, he can call all the algorithms in the same way, held out between various algorithms using algorithm class coupling.
Advantage 1: strategy class hierarchy strategy model for context defines a set of algorithms for reuse or inherited behavior helps draw out the common features of these algorithms.
2 advantages: simplifies the testing unit, because each class has its own algorithm, can be tested individually by its own interface.
When stuffing a different behavior in a class, it is difficult to avoid the use of conditional statements select the appropriate class behavior. These behaviors packaged in a separate class strategy may be to eliminate the use of conditional statements in these behaviors in the class.
Strategy mode is used to encapsulate the algorithm, but in time, we can use it to find almost any type of packaging rules, only to hear the different needs at different times of application of business rules, you can consider using strategy pattern in the analysis process the possibility of such change.
In the basic strategy mode, select a specific implementation of the responsibility borne by the client with the object and transferred to the context object. This in itself does not relieve the client needs to determine the choice of pressure, and the strategy pattern combined with a simple factory pattern, select a specific responsibility for implementation can also have a context to bear, to maximize alleviate the responsibility of the client. When the reflected and technologies may be further modified to avoid code.
Any changes are needed to the needs of cost.

Single responsibility principle
on a class, it should be only one reason for his cause change.
Software design really many things to do is to find the responsibility and the responsibility of those separated from each other. If you can think of more than one winter they go to a class, then the class will have more than one responsibility.

Open - Closed Principle
is said software entities (classes, modules, functions, etc.) should be extended, but can not be modified.
First, it is open for expansion (openfor extension) Second, the change is for closed (closed for modification)
designed under the open closed principle to face changes in demand may remain relatively stable, so that the system can be in after the first version We have introduced a new version.
No matter how close the module is closed there will be some changes can not cope, since can not be completely closed, the designer must be closed to make a choice on what changes he designed the module. He must guess the line is most likely the type of change, and what changes to isolate the abstract structure.
When the changes take immediate action in the initial writing code, assuming no change. When changes occur, we will create an abstract to isolate similar changes in the future. The face of demand changes to the program is carried out by adding new code, rather than changing existing code.
We hope that the development work launched soon know the changes that may occur. The longer the more difficult it is to identify possible changes to the waiting time, we must create the right abstractions.
Open Closed Principle is object-oriented design core. To deal with the program showing which parts of the frequent changes made abstract, however, for each part of the application are deliberately abstract same is not a good idea. As important as immature denial of abstraction and abstraction itself.

Dependency Inversion principle of
high-level modules do not rely on low-level module; abstract should not rely on the details, the details should depend on the abstract. It is to an interface for programming, not for reality programming.
Lee substitution principle
a software entity if the use is of a parent class, then it must apply to their subclasses, and he could not perceive the difference between parent and child class object. In other words, the software inside, the parent class are replaced his sub-class, the behavior does not change. Meaning: Only when the subclass can replace the parent class, a software unit of function is not affected, the parent can truly be reused, and the subclass can add new behavior on the basis of the parent class.
Rely on the reverse can be said to be a sign of object-oriented design, programming does not matter in what language, consider if writing is how to program for the abstract rather than to the details of programming that all dependencies program is terminated at an abstract class or interface, that is object-oriented design, in turn, is the design of the process.

Decorative patterns
may be required for controlling functions in series in the correct order.
Definition: an object to dynamically add some extra functions, increased functionality, the decorative pattern is more flexible than a subclass.
component is to define an object interface, it can only add functions to write dynamic objects. concretecomponent defines a specific object, you can also add some responsibilities to this object. decorator, decorative abstract class, inherited component, from outside the class to extend the functionality of the component class, but for the component, it is not need to know the existence of the decorator. As concretedecorator is a specific decorative objects, play a role in adding to the functional component.
Decorative pattern is to use setcomponent packaging objects, decorative objects on implementation of each and how to use this object separated, and each decorative objects only care about their function, do not need to care about how the object is added to the chain of them.
Only a concretecomponent class without abstract component class, decoraor class is a subclass of concretecomponent. Similarly, if there is only one class concretedecorator there is no need to build a separate decorator class, and can be a combination of responsibilities decorator and concretedecorator into a class.
Decorative pattern is a way to add more functionality to the existing function of the dynamic. When the system needs a new functionality is added to the old class in the new code, the new code is usually decorated with core responsibilities of the original class or main actors, the problem is in the main category added new class of fields, methods and logic , thereby increasing the complexity of the main class, and these new entrants things just to meet the needs of some special behavior only came back to perform in a given situation. The decorative pattern provides a very good solution, he put each function to be decorated in a separate class, and let this class include the object of his to be decorated, so when you need to perform special acts, the client can It requires a choice, according to the functions using sequential decorative packaging objects according to.
Advantages: function of moving the class from the class decorative removed, which can simplify the existing class. The core responsibilities effectively and decorative ribbon class apart. And related classes can remove duplicate decorative logic.

Proxy mode
proxy provides a proxy to control access to the object to other objects.
Proxy mode: 1 remote agent, that is, as an object to provide local representatives in different address spaces. This will hide the fact that there is an object with a different address space. 2 Alerts, is the need to create a lot of overhead objects based. Through his store to take a long time to instantiate the real object. 3 security agent used to control access permissions of the real object. 4 Smart guidelines means that when you call a real object, the agent handling some other things.

Factory pattern
biggest advantage is that simple factory pattern factory class contains the necessary logic to determine, based on the selection condition associated with the class of the client dynamically instantiated, for the client, in addition to rely on specific products. But when there are new demands to modify the factory class, contrary to the open closed principle.
A factory method pattern defines an interface for creating an object, but let subclasses decide which class of instances. The method of making a factory to instantiate the class to delay its subclasses. A method to achieve the factory mode, the client needs to decide which instance of the class factory to achieve operation type, the selection determination problem still exists, that is, the internal logic of the determination method of the factory plant simply moved to the client code. You want to add functionality, factory class could have been changed, it is now modify the client.

Prototype model
the prototype, with the specified type to create an object instance of a prototype, and create new objects by copying the prototype. In fact, the prototype model is then created another customizable from one object, and do not need to know any details of creation.
Usually in the case of initialization information is not changed, is the best way to clone. This hides the details of the object that is created, but also on the performance greatly improved. . If the field is a value type, then the field is performed bit-wise assignment, if the field is a reference type, then copy references but does not copy the objects referenced; therefore, a copy of the original object and reference the same object. Shallow copy, all variables are copied object contains the same value as the original object, and all other references are any natural object points to the original object. The objects referenced by the object to be copied are copied again. Deep copy the object reference variables pointing to the new objects copied, not the object of the original referenced.

Template Method
templatemothod skeleton algorithms defined in one operation, while deferring some steps to subclasses. Template Method lets subclasses may not change the structure of certain steps of an algorithm of the algorithm to redefine. Now with the inheritance, and this certainly makes sense to inherit, should be the template for subclass, all duplicate code should be up to the parent to go, rather than having each subclass to repeat.
When we have to complete at a consistent level of detail a process or series of steps, but to achieve its individual steps on a more detailed level may not be at the same time, we usually consider to deal with the template method pattern.
Template Method pattern is to achieve its advantage by moving to change the behavior of the superclass, subclass remove duplicate code. Template Method pattern is to provide a good platform code reuse. When the constant and variable behavior subclass method implementations are mixed together, the same behavior will be repeated in the subclass. We call these behaviors template behavior by moving to a single place template method pattern, thus helping subclass struggle to get rid of the constant repetition of the behavior.

Dimitris legal
lod also called the principle of least knowledge. Demeter, if the two classes do not have to communicate directly with each other, then the two classes can not be direct interaction. If a class needs to call a method of another class, you can forward the call through a third party.
In the structural design class, each class should try to reduce access to members. Dimitris legal system the fundamental idea is to emphasize the loose coupling between classes. Weaker coupling between classes, the better reuse, in a weakly coupled classes are modified, will not cause spread of a class are related.

Appearance model
facade provides a consistent interface subsystem is a set of interfaces, which pattern defines a high-level interface that makes the subsystem easier to use.
Use skin class: First, in the early stages of the design should have a sense of distinct layers of decomposition, such as the classic three-tier architecture, in the data access layer and the business logic layer, business logic and presentation layer needs to be considered and on the appearance and interlayer facade, which can provide a simple interface for complex subsystems, such coupling is greatly reduced. Secondly, during the development phase, subsystems often because of the constant evolution of reconstruction becomes more and more complex, increasing the appearance of the facade can provide a simple interface to reduce the dependencies between them. Third, while maintaining a large legacy system, the system may have been very difficult to maintain and expand, and develop a new system for the exterior facade class, to provide a more clear and simple interface design rough or highly complex legacy code, the new system allows objects to interact with the facade, facade legacy code to interact with all the complex work.

Model builder
will construct a complex object with his representation separation, so that the construction of the same process can create different representations, we have to use builder (builder) mode. If we use the builder pattern, then the user will just need to specify the type of construction you can get out of them, and specific details of the construction process and do not need to know.
builde is specified for the various components of a product to create an abstract object interfaces. concretebuilder specific builder, to realize the various components of the interface builder, construction and assembly. product of course is the product roles. director, a conductor is to build objects using interface builder, primarily used for creating complex objects, build order among these internal objects built is generally stable, but construction of internal objects usually faced with complex changes.
Benefits builder mode is to enable the construction of the code and a code indicating the separation, due to the construction of the hides is how to assemble the product, so if you need to change the internal representation of a product, just need to define a specific builder on it.
The builder was in when creating complex objects algorithm should be independent of the object as well as an integral part of their assembly method Applicable modes.

Observer Pattern
Observer Pattern observer: the definition of a dependent relationship of one to many observers have multiple objects simultaneously listening on a theme object. This theme object when the status changes, let notify all observer objects, enabling them to automatically update itself.
The system is divided into a series of collaborative classes have a very good side, and that is the need to maintain consistency between related objects. We do not want to maintain the consistency of the various types of tight coupling, this will maintain, extend and reuse all the inconvenience.
When you change an object you need to change other objects. And it does not know exactly how many objects to be varied, should consider using the observer pattern, when there are two aspects of an abstract pattern, is dependent on the one hand the other hand, when using the observer pattern can be encapsulated in both these independent manipulation of objects they independently change and reuse.
The observer pattern work done is in fact decoupled, so that both are dependent coupled with the abstract, rather than relying on concrete. So that the respective change will not affect the change on the other side.
A delegate is a type of method of reference. Once a delegate assignment method, the delegate behave exactly the method. The method may be used as delegate to any other method, with parameters and return values. Delegate can be seen as a function of the abstract, it is a function of l 'class' instance of a delegate representing the particular function.
A delegate can carry multiple methods, all methods are in turn evoke. Such methods can delegate object mounted does not need to belong to the same class.

Abstract factory pattern
novice programmers encounter problems, only use the time to settle.
Factory Method Pattern is to define an interface for creating an object, but let subclasses decide which class of instances.
Abstract factory pattern (abstract factory) to create a series of related or dependent objects interface, without specifying their concrete classes.
abstractproducta and abstractproductb are two abstract product, roducta1, roducta2 and productb1, productb2 is to achieve two specific categories of products abstract. ifactory is an abstract factory interface, which should contain all of the abstract methods of product creation. concretefactory1 and concretefactory2 is a specific factory. Run time, create an instance of a class concretefactory, this particular facility and then create a product to achieve a specific target, that is, to create different product objects, clients should use different concrete factory.
Benefits: Easy switching portfolio, due to the concrete factory class needs to occur only once during initialization In one application, which makes an application to change the concrete factory has become very easy, it only needs to change the concrete factory to use a different product configuration. He made specific separation process creates an instance of the client, the client is the interface to manipulate with their abstract instance, specific product class name is also specific separation plant, does not appear in the client code.
Note: In all plants where simple, can be considered a reflection switch or removed if, uncoupled to bring the branch determination.
If you do not stay up all night experienced a programmer to write a program, you can not be a good programmer, because he did not obsessed, so he will not have a big achievement.

State model
of object-oriented code that is actually hope to achieve the responsibility of decomposition.
Mode state (state), allowing the internal state of an object when a change to change their behavior, looks like the object has changed its class.
The main solution is to state mode when the conditional expression control of an object state transition is too complex situations. Determining the logic state of the different states is transferred to a series of classes which may be the complex logical judgment.
Benefits: The behavior associated with a particular state of localized and the behavior of different states separated. Is a specific state related behavior into an object, because all state related code are present in a concretestate in, so the new sub-class definition can easily add new states and transitions. This eliminates a large conditional branch statement. State mode distribution of the various logic state transition between the state of a subclass to reduce mutual dependence.
When the behavior of an object depends on his condition, and he must change his behavior according to the state at run time, you can consider using the state pattern.

Adapter mode
adapter, a converted class interface clients expect another interface. otherwise adapter mode such class not because of incompatible interfaces can work together with the work.
Software development, and behavior of the system when the data are correct, but does not match the interface, we should consider using the adapter, the purpose is to make a original target outside the control of an interface to match. Adapter mode main application and want to use some of the existing classes, but the interface with the complex and inconsistent with the environmental conditions.
When to use: Use an existing class, but if it's the interface, that is, its methods and your request is not the same, you should consider using an adapter mode.
Two things that made the same or similar class, but when he has to use a different interface. Client code can call the same unified interface for simpler, more direct, more compact.
In both not easy to modify the time and then use the adapter mode adaptation.

Memo mode
Memento, without violating encapsulation, capture and the internal state of an object, and to maintain this state outside the object. After such an object can be restored to the original saved state.
memento mode more suitable for more complex functions, but the need to maintain historical record attribute or category, or only when needed to save the properties of a few of the attributes, Originator can be restored to a previous state according to the saved information memento. If the command mode used in a system, the need to implement an undo function commands, the command mode may be used to store the memo mode manipulated revocation status. Use memo complex objects can be internal information other objects shielded. When the role of the state change when there may not be valid in this state, this time we can use temporarily stored memo will state recovery.

Combined mode
conposite, the combination of objects in a tree structure to represent "part - whole 'hierarchy. Combined mode enables the user to use a single consistent combinations of objects and object.
leaf is also referred to add and remove a transparent mode, the method used to manage all the sub-component objects declared, including add, remove the like. All subclasses implement this component interfaces are equipped with add and remove. The advantage is a leaf node and the branch node is no different to the outside world, they have exactly the same behavior interface. But the problem is also evident, because leaf class itself does not have add and remove functions, so he realized no sense.
When the discovery demand is reflected in part of the overall hierarchy want the user can ignore the different combinations of objects with a single object, all objects using a combination of a unified structure, you should consider using a combination mode.
Benefits: it defines the class hierarchy contains the basic objects and combinations of objects. The basic objects can be combined into more complex combinations of objects, and this combination of objects and can be combined, so constantly recursion, client code, any place used basic objects can be used in combination objects.
Users do not care about in the end is dealing with a leaf node or a combination of the formation process, which is no need to define a combination of written statements to determine the number of options. Combined mode so that the client can use the same combination of structural and individual objects.

Iterative mode
Iterative, there is provided a method of sequential access an object in each element of polymerization, and is represented by the interior of the object is not exposed. When you need to access an aggregate object, and no matter what these objects need to traverse, you should consider using an iterative mode. When you need to gather a variety of ways to traverse, consider using an iterative mode. When you need to gather a variety of ways to traverse, consider using an iterative mode. Traversing different aggregate structures to provide such as start, next, whether the end of the current Which of unified interface.
When you need to gather a variety of ways to traverse, consider using an iterative mode. Iterator pattern is the separation of the traversal behavior collection of objects, abstract an iterator class to be responsible, so that can be done without exposing the internal structure of the collection, but also allows external code transparent access to internal data collection.

Singleton
singleton, to ensure that only one instance of a class, and provide a global access his access point.
Usually we can make a global variable makes an object is accessed, but he can not prevent you from instantiating multiple objects. One of the best way is to make the class itself responsible for his unique instance. This class can ensure that no other instances can be created, and he can provide a method to access the instance. Singleton because singleton class encapsulates his only example, so that he can strictly control access to his client how and when to visit him. It simply is controlled access to the only instance.
lock is to ensure that when a thread is located in a critical area code when another thread does not enter the critical region. If another thread enters the lock code, he will have to wait until the object is released.
c # and the Common Language Runtime also provides a 'static initialization' method, which does not require developers to explicitly write thread-safe code, you can solve the multi-threaded environment that he is the problem of insecurity.
This approach is static initialization will be instantiated at their own is loaded, the image is called starving formula singleton class. If when first referenced, their only instantiated, it is called lazy formula singleton class.

Bridge mode
Bridge, the abstraction from its implementation so that they can be independently varied.
Object inheritance is defined at compile time Okay, so I can not change inherited from a parent class implements at runtime. Implementation subclass and its parent classes have very close dependencies, so that any changes in the parent class implementation will inevitably lead to changes in the subclass. When you need to reuse a subclass, if the inherited implementation does not fit to solve new problems, the parent class must be rewritten or replaced by other more appropriate class. This dependency limits flexibility and ultimately limit the reusability.
Means a polymerizable weak 'own' relationship is reflected in a target object can contain b, b but the object is not a part of the object; the synthesis has a strong relationship, and reflects part of the overall strict relationship, parts and the whole life cycle of the same.
Benefits: Priority object using synthetic / polymeric helps keep each class is encapsulated with you, and is focused on a single task. Such classes and class hierarchies will remain small-scale, and less likely to grow to uncontrollable monster.
What is the abstract separated from his realization that this is not to say, so abstract class and its derived class separation, because it does not make any sense. Realization refers to the abstract class and the derived class to implement his own object. Classification system may implement multiple angles, each class are likely to change, then let them put this isolated opposition changes to reduce the coupling between them angles. As long as real in-depth understanding of design principles, in fact, a lot of design patterns and application of the principles of order, perhaps in the use of design patterns unknowingly.

Command mode
which is actually 'behavior requester' and 'behavior implementers' tight coupling. A request queue or log requests, and a manipulation support undoable.
Command, encapsulating a request for an object, so that people make your clients using different parameterization of the request; the request queue or log requests, and support operations can be revoked.
1. He can more easily design a command queue; 2. In case of need, can be more easily included in the command log; 3. The method allows one to decide whether to accept the request is rejected requests. 4 can easily implement an undo and redo request; 5. Since add new specific command classes do not affect the other classes, thus adding new class specific commands easily. A command mode request to the object and knows how to manipulate a manipulation performed object segmentation opening.
Agile development principles tells us not to add to guess based on the actual function of the code is not required. If it is unclear whether a system needs to command mode, generally do not rush to implement it, in fact, when required by this model is not difficult to achieve reconstruction, only when really needed, such as undo / redo manipulation and other functions, the the original code refactoring command mode makes sense.

Chain of Responsibility pattern
Chain of Responsibility pattern (chain of responsibility): a plurality of object a chance to handle the request, in order to avoid the coupling between the sender and receiver of the request. The object is connected into a chain, and pass the request along the chain until an object handles it so far.
When a customer submits a request, the request is passed along the chain until an object handles a concretehandler it. The sender and the recipient have no other party with clear information, and the chain of the object does not know the structure of the chain. The result is interconnected objects simplify the chain of responsibility, they need only to keep a reference to its successor, without the need to keep it all the candidates accept references. May increase or modify the structure of the processing of a request at any time. Enhancing the flexibility of assigning responsibilities to objects.
A request is likely to end of the chain are not treated, or because there is not the correct configuration process.

Intermediary model
Although a system is typically divided into a number of objects which can increase reusability, but interconnected objects surge will reduce the reusability. So that a large number of connections objects can not work without the support of other objects, the system performance of an indivisible whole, therefore, the behavior of the system will be very difficult to make any major changes.
mediator, with an intermediary object that encapsulates set of objects interact. Mediator the respective objects do not explicitly refer to each other, so that it loosely coupled, and can be changed independently of their interaction with each other.
Intermediary model in the system is easy to use, and very easy to misuse the system. When the system of the target group 'many to many' interactions, do not rush to use the intermediary model, and reflect on your first system in the design is not reasonable. the mediator occurs each coupling reduces the colleague, such changes can be independent and multiplexing the respective classes and colleague mediator, since the abstract how collaboration objects, the intermediary as an independent concept and encapsulated in an object, so that the object of attention shifts from their own behavior object to the interaction between them up, we are standing in a broader perspective on the system.
Since concretemediator centralized control, then put into a complex interaction complexity Mediator, which makes any Mediator becomes larger than a concretecolleague are complicated. Intermediary model generally applied to a set of objects and a well-defined but complex ways of communication occasion, and want to customize the behavior of a distributed across multiple classes, but do not want to generate too many sub-class of applications.

Flyweight
flyweight, Use sharing to support a large number of fine-grained objects. Flyweight pattern to avoid the overhead of a large number of very similar class. In programming, the class may need to generate a large number of instances of fine-grained to represent data. If these examples can be found in addition to several parameters are substantially the same, and sometimes can be greatly reduced by the required number of instances of the class. If those parameters can move outside the class instance, when they will be passed in the method call, you can significantly reduce the number by sharing a single instance.
If an application to try a large number of objects, and these objects caused a lot of overhead storage you should consider using; there is the most state of the object may be outside the state, if you delete an object outside the state, you can use a relatively small many shared object substituent group object, then you can consider using Flyweight.

Interpreter pattern
Interpreter, a given language, a grammar definition of his representation, and define an interpreter, the interpreter uses the representation to interpret sentences in the language.
When there is a need to explain the implementation of the language, and you can express the sentences in the language is an abstract syntax tree, you can use the interpreter mode. Easy to change and expand the grammar, because this mode uses classes to represent grammar rules, you can use inheritance to change or extend the grammar . Grammar is relatively easy to implement, because the implementation class defines an abstract syntax of each node substantially similar books, which are easy to write directly.
Interpreter pattern deficiencies, Interpreter pattern is the grammar of each rule defining at least one class and therefore contains many rules of grammar can be difficult to manage and maintain. It recommended when grammar is very complex, using other techniques such as parser or compiler generator to handle.

Visitor pattern
visitor, showing an actuating element of each effect object structure. He makes you can not change the definition of the class under the premise of each element acting on the operation of these new elements.
Visitor pattern applied to the data structure is relatively stable system, he coupled between the data structure and acting on the actuating structure to be freed, so that manipulation can be relatively freely set evolution. Purpose is to make the visitor pattern is separated from the process data structure. When the system has relatively stable and easy to change the structure of the algorithm, then use of visitors is more appropriate, such as visitor pattern manipulation algorithm can be easily increased. Visitor pattern is to increase the advantage of the new operation is very easy, because to do gymnastics to add new meaning to add a new visitor. The visitor pattern of behavior related to the concentration of a visitor object.
That is the disadvantage of visitors to add new data structure becomes difficult.
---------------------
Author: watson2016
Source: CSDN
Original: https: //blog.csdn.net/Watson2016/article/details/51883713
Disclaimer: This article as a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin blog.csdn.net/u014421422/article/details/87921053