First, Introduction
After this period of time on the design pattern of learning, their feelings are still a lot of, because I now write code, often think of here can use what design mode to reconstruct. So, after you finish the design pattern, you feel it will slowly affect the way you think about writing code. Here is a summary of the design pattern, one can be a comb for all design patterns, and can do an index to help you collect.
PS: In fact, I have seen all the design patterns very early, but did not write a blog, but soon forgotten, and did not play any role, this time to summarize the form of the blog, found that the effect is still very obvious, because through this summary of the way, I understand it more deeply, but also remember the more secure, Also affect their own normal realization of the function of thinking. So, I encourage you to take notes to sort out what you've learned so that you can understand deeper and better, and I'll write about it, and then I'm going to write a series of articles about WCF.
In fact, WCF content is very early also read, and blog Park also has a lot of predecessors write very good, but, I think I still need to summarize, because only this, knowledge is their own, others write how good, you look after, actually still others, so encourage you a few points (for these points, but also a reminder of their own):
- To do the actual combat in other people's blog examples;
- After the implementation of the summary, you can write a blog can also record their own cloud notes, etc.;
- Think about whether you can expand and extrapolate.
Ii. Principles of Design
The fundamental reason to use design patterns is to adapt to changes, improve code reuse, and make software more maintainable and extensible. And, in the design, we also need to follow the following principles: the single Responsibility principle, the open closure principle, the Richter substitution principle, the dependency inversion principle, the interface isolation principle, the synthetic reuse principle and the Dimitri law. Each of the design principles is described below.
2.1 Single Duty principle
As far as a class is concerned, there should be only one cause for it to change. If a class takes on too much responsibility, it is tantamount to coupling these responsibilities, a change in one's responsibilities may affect other responsibilities, and the coupling of multiple responsibilities can also affect reusability.
2.2 Opening and closing principle (open-closed Principle)
The open and closed principle is the OCP (open-closed principle abbreviation) principle, which emphasizes that a software entity (referring to classes, functions, modules, etc.) should be opened to the extension and shut down for modification. That is, each time a change occurs, the behavior of the existing type is enhanced by adding new code instead of modifying the original code.
The best way to conform to the open and close principle is to provide an intrinsic interface and then have all potentially changing classes implement the interface, allowing the fixed interface to interact with the related object.
2.3 Richter Substitution principle (Liskov Substitution Principle)
Liskov Substitution PRINCIPLE,LSP (Richter substitution principle) refers to subclasses that must replace their parent type. In other words, the program behaves the same when the child class replaces the parent class during software development. The parent class can be truly reused only when the subclass has replaced the parent class, and the child class may add new behavior based on the parent class, when the functionality of the software is not affected. To take a look at an example that violates the LSP principle, the exact code is as follows:
public class Rectangle {public virtual long Width {get; set;} Public virtual long Height {get; set;} } Square public class Square:rectangle {public override long Height { get { return base. Height; } Set { base. Height = value; Base. Width = value; } } public override long Width { get { return base. Width; } Set { base. Width = value; Base. Height = value;}} } Class Test {public void Resize (Rectangle r) {while (r.height >= r.width) { r.width + = 1; } } var r = new Square () {Width = ten, Height = ten}; New Test (). Resize (R); }
The above design, as noted above, when executing the Smarttest resize method, if a rectangle object is passed in, when the height is greater than the width, the width is automatically increased until the height is exceeded. However, if a square object is passed in, it will fall into a dead loop. At this point the root cause is that the rectangle cannot be the parent of the square, and since there is a problem, you can refactor it so that both of them inherit from the Quadrilateral class. The refactored code looks like this:
Quadrilateral public abstract class quadrangle {public virtual long Width {get; set;} Public virtual long Height {get; set;} } Rectangle public Class Rectangle:quadrangle {public override long Height {get; set;} public override long Width {get; set;} } Square public class Square:quadrangle {public long _side; Public Square (long side) { _side = side; } } class Test {public void Resize (quadrangle R ) { while (r.height >= r.width) { r.width + = 1; } } static void Main (string[] args) { var s = new Square (ten); New Test (). Resize (s); } }
2.4 Dependency Inversion principle
Dependency inversion (dependence inversion Principle, DIP) principle refers to the abstraction should not be dependent on the details, the details should be dependent on the abstraction, that is, the proposed "interface-oriented programming, rather than implementation-oriented programming." This can reduce the coupling between the customer and the specific implementation.
2.5 Interface Isolation Principle
The interface isolation principle (Interface segregation Principle, ISP) is that it is better to use multiple specialized interfaces than to use a single total interface. In other words, do not allow a single interface to assume too much responsibility, but should separate each responsibility into a number of specialized interfaces, interface separation. An overly bloated interface is a kind of pollution to the interface.
2.6 Synthetic multiplexing Principles
The principle of synthetic multiplexing (Composite reuse Principle, CRP) is to use some existing objects within a new object to make them part of the new object. The new objects are reused for the purpose of the used functionality by delegating to these objects. Simply put, try to use composition/aggregation and try not to use inheritance.
In order to use the principle of synthetic reuse, the relationship between "has-a" and "is-a" should be distinguished first.
"Is-a" refers to a class that is "one" of another class, a relationship that belongs to it, and "has-a" is different, which indicates that a role has a certain responsibility. A common cause of incorrect use of inheritance instead of aggregation is to mistakenly treat "has-a" as "is-a". For example:
In fact, employees, experiences, students describe a role, such as a person is "manager" must be "employee". In the above design, a person can not have multiple roles at the same time, is "employees" can no longer be "student", this is obviously unreasonable, because now many in-service graduate student, even if the employee is also students.
The above design error stems from the "character" hierarchy and "human" hierarchy structure confused, mistakenly "has-a" as "is-a". The specific solution is to abstract a role class:
2.7 Dimitri Law
The Dimitri rule (law of Demeter,lod) is also called the least knowledge principle (Least knowledge principle,lkp), which means that an object should have as little knowledge of other objects as possible. That is, a module or object should be as small as possible interaction with other entities, so that the system function module is relatively independent, so that when a module is modified, the less affected modules will be expanded more easily.
Some other statements about the Dimitri rule are: communicate only with your direct friends; don't talk to strangers.
The Dimitri rule is used in the appearance pattern (facade pattern) and the mediator pattern (mediator pattern).
Third, the creation mode
Creating patterns is the pattern used to create objects, abstracting the process of instantiation. All the creation patterns have two things in common. First, they encapsulate what specific classes of information the system uses, and second, they hide how instances of these classes are created and organized. The creation pattern includes a singleton pattern, a factory method pattern, an abstract factory pattern, a builder pattern, and a prototype pattern.
- Singleton mode: Solve the problem of instantiating the number of objects, such as the factory in the abstract factory, object pool, and so on, in addition to Singleton, the other creation mode is to solve the new coupling relationship.
- Abstract Factory: Creates a series of interdependent objects and can change the series at run time.
- Factory Method: Create a single object that is used in the abstract factory.
- Prototype mode: Creates a new object by copying the prototype.
Factory methods, abstract factories, builders all need an extra factory class to instantiate "one object", while prototype clones "variable objects" through prototypes (a special factory class).
They are described in detail below.
3.1 Single-case mode
Singleton mode refers to ensuring that a class has only one instance and provides a global access point. Solves the problem of the number of entity objects, while the other builder models are to solve the coupling problem caused by new. The main points of implementation are:
- Class has only one instance. Q: How can I guarantee it? A: The private constructor ensures that the class cannot be instantiated outside the class
- Provides a global access point. Q: How do I do that? A: Create a static method that returns the class object
The structure diagram for the singleton pattern is as follows:
3.2 Factory Method mode
The factory method pattern refers to defining a factory interface that creates an object, whose subclasses decide which class to instantiate and defer the actual creation to the subclass. It emphasizes the change of "single object" . The main points of implementation are:
- Defines a factory interface. Q: How do I do that? Answer: Declare a factory abstract class
- Objects are created by their specific subclasses. Q: How to achieve it? A: Creation is derived from the factory abstract class, that is, the specific factory to create specific products, since the creation of products, naturally requires product abstraction classes and specific product classes.
Its specific UML structure diagram is as follows:
In the factory method pattern, the factory class has a parallel hierarchy with the specific product class, which is a one by one correspondence between them.
3.3 Abstract Factory mode
Abstract Factory mode refers to the provision of an interface that creates a series of related or interdependent objects, allowing the client to create product objects in multiple product families without having to specify a specific type of product, emphasizing changes in " Series objects" . The main points of implementation are:
- Provides an interface for a series of objects. Q: How to achieve it? A: Provides an abstract interface for multiple products
- Create multiple product objects in multiple product families. Q: How do I do it? A: Each specific factory creates multiple product objects in a product family, and multiple specific factories can create multiple objects in multiple product families.
The specific UML structure diagram is as follows:
3.4 Builder Mode
The builder model refers to the separation of the internal representations of a product from the construction of the product, which enables a construction process to produce a product object of a specific internal representation. Emphasis is placed on the process of product construction. The main points of implementation are:
- The internal representation of the product is separated from the construction process of the product. Q: How can I split them up? A: Do not put the product construction process in the product class, but by the builder class to take charge of the construction process, the product of the internal representation in the product class, so do not split open it.
The specific UML structure diagram is as follows:
3.5 Prototype Factory mode
Prototype mode refers to a prototype object that indicates the type of object to be created, and then uses the copied method to create more of the same type of object. The main points of implementation are:
- Gives a prototype object. Q: How do I do that? A: Very simple, just give a prototype class is good.
- Create the same type object by copying the method. Q: How is it implemented? For:. NET can call the MemberwiseClone method directly to implement a shallow copy
The specific UML structure diagram is as follows:
Four, structural model
Structured mode, as the name implies, is the structure of classes and objects, which are primarily used to handle classes or object combinations. It includes two types, one is the class structure pattern, refers to the use of inheritance mechanism to combine the interface or implementation, and the other is the object structure pattern, refers to the method of combining objects to achieve new functions. It includes adapter mode, bridging mode, adorner mode, combined mode, appearance mode, and the enjoy meta mode and proxy mode.
- Adapter mode focuses on the conversion interface, matching interfaces that do not match the docking
- Bridging mode focuses on the separation of interfaces and their implementation, supporting multi-dimensional changes
- The combination mode focuses on the unified interface, the "one-to-many" relationship into a "one-to-one" relationship
- Decorator mode focuses on stabilizing the interface, in this case extending the function to the object
- The appearance mode focuses on simplifying the interface, simplifying the dependencies between the component system and the external client program
- The enjoy meta-mode focuses on preserving interfaces and optimizes object storage using shared technology internally
- The agent mode focuses on the borrowing interface and adds the indirect layer to achieve flexible control.
4.1 Adapter Mode
The adapter mode is intended to transform the interface, which makes it possible to work with two classes that would otherwise not work together, so it is often used for reuse of class libraries, code migrations, and so on. For example, the DataAdapter class applies the adapter pattern. The adapter mode includes the class adapter mode and the object adapter pattern, as shown in the class adapter mode on the left and the object adapter mode on the right.
4.2 Bridging mode
Bridging mode is designed to decouple abstraction from implementation so that they can vary independently. In other words, bridging mode will further abstract the implementation details of the original base class, construct it into an implementation structure, and then transform the original base class into an abstract hierarchical structure, so that the system can change independently in multiple dimensions, and the structure diagram of the bridging pattern is shown below.
4.3 Decorator mode
Decorator mode, also known as packaging (Wrapper) mode, can dynamically add some additional functionality to an object, and decorator mode is more flexible than inheriting the generation of subclasses. Although decorator mode can dynamically attach responsibilities to objects, it also creates small objects that increase the complexity of the system. The specific structure diagram is shown below.
4.4 Combination Mode
The combined mode is also known as partial-overall mode. The combined mode combines objects into a tree structure that represents the relationship between the whole and the part. The combined mode allows the client to treat a single object and a composite object equally. As in. NET controls in WinForm, TextBox, label, and other simple controls inherit from the control class, while groupbox such a combination control is also inherited from the control class. The detailed structure diagram of the combined pattern is shown below.
4.5 appearance mode
In the system, the client often needs to interact with multiple subsystems, which causes the client to change as the subsystem changes, allowing the client to be decoupled from each subsystem using the appearance mode. The appearance pattern refers to providing a consistent façade for a set of interfaces in a subsystem, which provides a high-level interface that makes the subsystem easier to use. such as the Customer Commissioner of telecommunications, you can let the customer commissioner to complete the charges, modify the package and other services, without having to interact with the various subsystems. The concrete class structure diagram looks like this:
4.6 Enjoy meta mode
In a system where we need to reuse an object, it is a waste of time to use the new operator repeatedly to create this object, which is a huge drain on system resources, since every time you use the same object, why can't we share it? This is also the reason that the enjoy meta mode appears.
The enjoy meta-mode uses shared technology to effectively support fine-grained objects for sharing. In the. NET class library, the implementation of the string class uses the enjoy meta-pattern, which uses string-resident pooling to share strings. For more information, see the blog: http://www.cnblogs.com/artech/archive/2010/11/25/internedstring.html. The specific structure diagram for the enjoy meta-mode is shown below.
4.7 Proxy Mode
In system development, some objects can be accessed by a proxy object because of network or other barriers that cannot be accessed directly. Operations such as invoking a Web service in. Net.
The proxy mode refers to providing a proxy to an object and controlling access to the original object by the proxy object. The specific structure diagram is shown below.
Note: What is the difference between appearance mode, adapter mode and proxy mode?
Answer: These three patterns are identical in that they are both a middle tier between the client and the real used class or system, which makes the client invoke the real class indirectly, except that the application is different from the intended situation.
The main difference between the proxy mode and the appearance mode is that the proxy object cannot access the object directly, only the proxy object provides access, while the façade object provides a simplified access invocation interface to each subsystem, while the adapter pattern does not need to invent a proxy to reuse the original interface. The appearance mode is the definition of the new interface, while the adapter is reusing an original interface.
In addition, they apply the different stages of design, the appearance pattern is used in the design of the early stage, because the system needs to rely on the appearance of the pre-design, and when the adapter is designed to complete, when the completion of the design of the class cannot work together, the adapter mode can be used. In many cases, however, the use of adapter patterns is considered in the early stages of design, such as when a large number of third-party application interfaces are involved; proxy mode is when the pattern is complete and wants to be made available to other clients as a service, while other clients can access the module using proxy mode.
In summary, the proxy pattern provides an interface that is consistent with the real class, designed to be used by proxy classes to access real classes, which are designed to simplify interfaces, and adapter patterns are designed to transform interfaces.
V. Behavioral patterns
Behavioral patterns are abstractions that divide responsibilities and algorithms between different objects. Behavior patterns are not just about classes and objects, but also about the interactions between them. Behavioral patterns are divided into classes of behavioral patterns and object behavior patterns of two.
- The behavior pattern of a class-the use of inheritance relationships to distribute behavior among several classes.
- The behavior pattern of an object-the way that objects are aggregated to assign behavior.
Behavioral patterns include 11 modes: Template method mode, command mode, iterator mode, observer pattern, Mediator mode, state mode, policy mode, responsibility chain mode, visitor mode, interpreter mode, and Memo mode.
- Template method Pattern: Encapsulates the algorithm structure, defines the algorithm skeleton, supports the algorithm sub-step change.
- Command pattern: Focus on encapsulating the request as an object, supporting the change of the request, by abstracting a set of behaviors into objects and implementing decoupling between the requester of the behavior and the person implementing the behavior.
- Iterator pattern: Focus on encapsulation of specific domain changes, support the change of the collection, shielding the complex structure of the collection object, provide transparent traversal of the client program.
- Observer pattern: Focus on Encapsulation object notification, support the change of the communication object, realize the object state change, notify the object that depends on it and update.
- Mediator mode: Focus on the interaction between encapsulated objects, by encapsulating the complex interactions between a series of objects, so that they do not need to explicitly cross-reference, to achieve decoupling.
- State mode: Focuses on encapsulating state-related behavior, supporting state changes by encapsulating the state of an object and altering its behavior when its internal state changes.
- Policy mode: Focus on the encapsulation algorithm, support the change of the algorithm, by encapsulating a series of algorithms, so that can be independent of the customer replacement algorithm at any time.
- Responsibility chain Model: Focus on Packaging object responsibility, support the change of responsibility, through the dynamic construction of responsibility chain, to achieve transaction processing.
- Visitor pattern: Focus on encapsulating object manipulation changes, supporting the addition of new operations to the class structure at run time, and defining new operations that act on these class instances in the class hierarchy without changing the categories.
- Memo mode: Focus on Packaging object state changes, support state saving, recovery.
- Interpreter mode: Focus on packaging specific areas of change, support the frequent changes in domain issues, the specific areas of the problem expressed as a grammatical rule of the sentence, and then build an interpreter to explain such sentences, so as to achieve the purpose of solving the problem.
5.1 Template Method mode
In real life, there are paper templates, CV templates and so on. In real life, the concept of a template is given a certain format, and then all other people who use the template can implement it according to their own needs. The same is true for template methods.
The template method pattern is to define an algorithm skeleton in an operation in an abstract class, and defer the implementation of some concrete steps into subclasses. The template method allows subclasses to redefine the specific steps of the algorithm without changing the structure of the algorithm, thus achieving the effect of reusing code. The specific structure diagram is shown below.
An example of a template method for making a dish in life. Structure diagram
5.2 Command mode
The command pattern belongs to the behavior pattern of an object, and the command pattern encapsulates a request or action into an object by abstracting the command to separate the responsibility for the command and the responsibility for executing the command. The implementation of the command pattern can provide undo and redo functions for the command. The specific structure diagram is shown below.
5.3 Iterator Mode
The iterator pattern is based on the collection object, for the collection object, it inevitably involves the addition of the collection element delete operation, also certainly support the operation of iterating over the collection element, if the traversal operation is also placed in the collection object, the collection object will assume too much responsibility, at this time can be separated by responsibility, Put the traversal of the collection in another object, which is the iterator object.
The iterator pattern provides a way to sequentially access individual elements in a collection object without exposing the object's internal representation, so that the internal structure of the collection is not exposed and external code transparently accesses the inner elements of the collection. The specific structure diagram is shown below.
5.4 Observer patterns
In real life, there are observer patterns everywhere, such as subscription numbers, subscription blogs, and QQ Weibo that focus on friends, all of which are application of the observer pattern.
The Observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time, and the subject object notifies all observer objects when the state changes, enabling them to automatically update their behavior. The concrete structure diagram is as follows:
5.5 Broker Mode
In real life, there are many intermediary patterns of the figure, such as the QQ game platform, chat room, QQ Group and SMS platform, these are the intermediary model in the real life of the application.
A mediator pattern that defines a mediation object to encapsulate the interaction between a series of objects. Intermediaries do not need to explicitly reference each other between objects, which reduces coupling and can independently change the interaction between them. The specific structure diagram is as follows:
5.6 State Mode
Each object has its corresponding state, and each state corresponds to some corresponding behavior, and if an object has more than one state, then there are many behaviors. Then the judgment of these States and the behavior done according to the state result in multiple conditional statements, and if you add a new state, you need to change the previous existing code. Such a design is clearly against the opening and shutting principle, the state pattern is to solve such problems.
State mode--allows an object to automatically change its behavior when its internal state changes, and the object looks like it has changed its class. The specific structure diagram is as follows:
5.7 Policy mode
In real life, China's income tax is divided into enterprise income tax, foreign investment enterprises or foreign enterprise income tax and personal income tax, according to these 3 kinds of income tax, each calculation of different ways, personal income tax has a personal income tax calculation method, and enterprise income tax has its corresponding calculation. If we do not adopt a policy model to achieve such a requirement, we will define an income tax class that has an attribute to identify the type of income tax, and a Calculatetax () method for calculating taxes, which needs to be judged on the tax type in the body of the method, The If-else statement is adopted to calculate the income tax for different tax types. Such an implementation can really solve this scenario, but such a design is not conducive to expansion, if the system later need to add a kind of income tax, at this time have to go back to modify the Calculatetax method to add a more judgment statement, so clear against the "open-closed" principle. At this point, we can consider using the strategy model to solve this problem, since the tax method is the change part of this scene, at this time naturally can think of the tax method abstraction, which is the essence of the implementation of the strategy model.
The strategy pattern is the wrapper over the algorithm, which divides the responsibility of the algorithm and the algorithm itself, delegating it to different objects. The strategy pattern usually wraps a series of algorithms into a series of strategy classes. In a word, the policy pattern is--"encapsulate each algorithm into different policy classes so that they can be interchanged." Here is the structure of the policy pattern:
5.8 Responsibility Chain Mode
In real life, there are many requests not a person said, such as the salary at the interview, less than 10,000 of the salary may be decided by the technical manager, but 10,000 ~ 10,005 of the salary may not be the technical manager of the right to approve, may need to request the approval of the technical director.
Chain of responsibility mode-a request requires multiple objects to be processed, thus avoiding the coupling between the sender and the receiver of the request. Connect the objects to a chain and pass the request along this chain until an object has processed it. The concrete structure diagram is as follows:
5.9 Visitor Mode
The visitor pattern is to encapsulate some operations that are applied to a data structure. Once these operations need to be modified, the data structure that accepts the operation can be saved unchanged. The visitor pattern is suitable for a system with relatively stable data structures, which reduces the coupling between the structure and the operations acting on it, making the set of operations relatively free to change. The concrete structure diagram is as follows:
5.10 Memo Mode
In the life of mobile phone address Book memo, operating system backup point, database backup, etc. are the application of Memo mode. The memo mode captures the internal state of an object without destroying the package, and saves the state outside of the object so that it can be restored to its previous state. The specific structure diagram is as follows:
5.11 Interpreter Mode
Interpreter mode is a relatively less used mode, so I do not have a thorough study of the pattern, in life, the role of English-Chinese dictionary is to achieve English and Chinese translation, which is the application of the interpreter mode.
The interpreter pattern is given a language, defines a representation of its grammar, and defines an interpreter that uses that representation to interpret the sentences in the language. The specific structure diagram is as follows:
Vi. Summary
23 Kinds of design patterns, in fact, the predecessors summed up the way to solve the problem, their pursuit of the purpose is to ensure that the system of low coupling high cohesion, guiding their principles is nothing more than package changes, a single responsibility, oriented interface programming design principles. After that, I will continue to share their own WCF learning process, although there are many of the blog in the WCF series, I feel that there is no need to write, feel that will be used on the line, but do not write, the total feeling of knowledge is not their own, feel no depth, so still want to write such a series, I hope you have a lot of
PS: Many forums have seen beginners ask, WCF now there is no need to delve into such problems, because they think that these technologies may be outdated, and perhaps then Microsoft launched a new SOA implementation, it is not the time to learn in depth, so it is not necessary to learn in depth, know how to use it. I had the same feeling about the problem before, but now I think that although WCF technology may be replaced, but in-depth understanding of a technology, the focus is not to know some of the more advanced API calls Ah, but to understand its implementation mechanism and way of thinking, even if the latter technology is replaced, The mechanism behind it is certainly similar. So in-depth understanding of a technology, you will feel the new technology familiar with its feel relaxed. And, after you have a thorough understanding of a technology, you can also say in the interview that you have mastered the technology very well, and do not say that the usual use of many, once in-depth questions do not know the principle behind the implementation. That's why I'm writing the WCF series. I hope this opinion is helpful to some beginners.
The design pattern of C #