Design Patterns - Introduction and principles

1. The purpose of points

Creating type model: 

  singleton, factory pattern, abstract factory pattern, the builder pattern, prototype model 

structural model: 

  adapter mode, bridge mode, decorative patterns, the combination mode, aspect mode, Flyweight, Proxy mode 

behavioral patterns: 

  template method mode, command mode, the iterator pattern, observer pattern, intermediary model, the memo mode, the interpreter pattern, state pattern, strategy pattern, duty chain, visitor pattern

The scope of points

Class pattern: for the relationship between treatment classes and subclasses, these relationships are established through inheritance, it is static, then finalized at compile time. Factory method in GoF, (s) adapter, a template method, belong to the interpreter mode. 
Object model: a relationship between processed, these relationships can be achieved by a combination of the polymerization or at run time may vary, more dynamic. In addition to the four or more GoF, the other is object model.

It features 23 kinds of design patterns 3.GoF

1) Single Example (the Singleton) mode: only generate an instance of a class, a class provides global access point for external acquire this example, which is limited cases of expansion mode. 
2) Prototype (the Prototype) mode: an object as a prototype, be copied by a plurality of cloned prototypes of a new instance, and the like. 
3) factory method (Factory Method) mode: define an interface for creating a product, what products produced by the subclasses determined. 
4) Abstract Factory (AbstractFactory) mode: create a product family of interfaces, each subclass can produce a series of related products. 
5) Builder (Builder) mode: a complex object into a plurality of relatively simple part, create them according to different needs and, respectively, into the final construct complex objects. 
6) proxy (Proxy) mode: to provide a proxy to control access to the object as an object. I.e., indirectly via a proxy client to access the object, thereby limiting, enhance or modify some features of the object. 
7) Adapter (Adapter) mode: converting a class interface clients expect another interface, such as those due to incompatible interfaces based otherwise not able to work together with the work. 
8) bridge (Bridge) mode: an abstraction and separation, so that they may be varied independently. It is achieved by a combination relationship instead of inheritance, and abstraction implemented to reduce the dimensions of the two variable degree of coupling. 
9) decoration (Decorator) mode: Dynamic Object to add some responsibilities, namely to increase its extra features. 
10) Appearance (the Facade) mode: providing a consistent interface to multiple complex subsystems, these subsystems are more easily accessible. 
11) Flyweight (Flyweight) mode: Use sharing to support effective reuse a lot of fine-grained objects.
12) a combination of (Composite) mode: the objects into the hierarchy tree, so that the user has access to the same combination of the object and the individual objects.
13) The method of the template (TemplateMethod) mode: the definition of a skeleton algorithm operation, some steps of the algorithm to delay subclass, so that subclasses can without changing the structure of the algorithm redefine certain steps of the algorithm . 
14) Strategy (Strategy) mode: it defines a set of algorithms, and each algorithm package together, so that they can replace each other, and the algorithm change does not affect customers using the algorithm. 
15) a command (Command) mode: Encapsulate a request for an object, so that execution of the request and Responsibility requesting separated. 
16) duty chain (Chain of Responsibility) mode: the request passed from one object to the next in the chain, up until the request is acknowledged. Removing the coupling between objects in this way. 
17) state (State) mode: allows an object to change its capacity when its internal state changes. 
18) observers (Observer) mode: many relationship between a plurality of objects, when an object is changed, the change is notified to the plurality of other objects to affect the behavior of other objects. 
19) Mediator (Mediator) mode: Define a mediation object is to simplify the interaction between the original target, reducing the coupling between objects in the system, so that between each other without having to know the original target. 
20) iterator (the Iterator) mode: to provide a sequential access method to a series of data objects in the polymerization, the polymerization without exposing the internal representation of the object. 
21) the visitor (Visitor) mode: a collection of elements without changing the premise of providing a variety of ways to access a set of each element, i.e. each element has a plurality of visitor access objects. 
22) Memorandum (Memento) mode: without destruction of the package, obtains and stores the internal state of an object, in order to recover it later. 
23) interpreter (Interpreter) Mode: how to define the grammar provides language and interpretation of language sentence, i.e., interpreter.

 4. Relationship between classes

In software systems, like not exist in isolation, there are various relationships between classes. The degree of coupling between the classes and the classes are arranged from weak to strong, the UML class diagram are the following relation: dependency relationship, the relationship between the polymerization, combination relation, and to achieve generalization relationship. Wherein the coupling degree of generalization and implementation are equal, they are the strongest.

1) dependence 
 dependency (the Dependency) relationship is a relationship to use, which is the weakest coupling between objects in an association manner, a temporary association. In the code, a method of a class by accessing local variables, parameters or methods of static method call to 
 some methods in another class (the class dependent) to accomplish some of the functions. 2 ) association  association (Association) relationship is a relationship between the object reference, is used to represent a kind of link between the object and the object of another class, such as teacher and student, master and apprentice, husband and wife and so on. Association is the most common kind of relationship between classes
 is divided into a general relationship, the relationship between the polymerization and combination relation. Usually we first introduce associated 3 ) Polymerization relationship  polymerization (Aggregation) relationship is a relationship, the relationship is strong, and the relationship between the integral part, are has- relation of a. 4 ) combining relationship
 composition (Composition) relationship is also associated with a relationship, but also shows the relationship between whole-part type, but it is a stronger relationship between the polymerization is contains- A relationship. 5 ) turned generalization relationship (the Generalization) relationship is a relationship of the maximum degree of coupling between objects, and shows the general special relationship, the relationship between parent and child classes, that is an inheritance is IS- A Relationship. 6 ) implemented to achieve the relationship (Realization) relationship is between the interface and implementation class. In this relationship, the class implements an interface, operating class implements all the abstract operation interface declared.

5. Principles

1) Open Closed Principle

Origin: Open Closed Principle (Open Closed Principle, OCP) proposed by Brandt • Meyer (Bertrand Meyer), software entities should be open for extension, but closed for modification. 
   Software entity:. A project divided modules b classes and interfaces c methods. 

Meaning: when changing needs of the application, without modifying the software entity, source code or binary code, you can extend the functionality modules, so that meet the new demand. 
Role:   A. Impact on software testing   software to comply with the principle of opening and closing, then, requires only a software test code to test for extensions on it, because the original test code still works correctly.   B. Improve the code reusability    smaller the particle size, the greater the possibility of being multiplexed; in object-oriented programming, and the atomic abstract programming can improve code reusability.   C. You can improve software maintainability of   compliance with the principle of opening and closing software, high stability and strong continuity, making it easy to extend and maintain.
Method:   may be opened and closed by the principle of "abstract constraint change package", i.e. through the software interface or abstract class defines a relatively stable entity abstraction layer, and the same package variables embodied in the same class .  
  Because the abstract good flexibility and adaptability, as long as the abstract rational, can remain stable software architecture. The software variable details can be extended abstract is born from the realization of class, when the software needs to change, just as required
  to re-implement a derived class to extend it.

2) Richter substitution principle

Origin: Richter Substitution Principle (Liskov Substitution Principle, LSP) by Ms. Laboratory for Computer Science at MIT Rees Cove (Liskov) 1987 's "Summit of object-oriented technology" (OOPSLA) 
   published an article article "data abstraction and hierarchy" (data abstraction and hierarchy) was brought out, she asked: inheritance must ensure that the superclass owned properties are still set up in a subclass.
Definition: Richter replace the main principles set out some principles concerning inheritance, that is, when should use inheritance, when it should not use inheritance, and it contains principles. Richter replace originally inherited base reuse, which reflects the base class and subclass
   relationships between, it is the principle of complementarity opening and closing, is the specification for concrete steps to achieve the abstract. Role:    . A substitution principle Richter is one important way to achieve the principle of opening and closing.    B. It overcomes the shortcomings of inheritance override the parent class due to deterioration of reusability.    C. It is to ensure the correctness of the action. That kind of expansion will not introduce new errors to existing systems, it reduces the possibility of error codes.
Method:    Leeb is replaced by the principle of popular terms: subclass can extend the functionality of the parent class, but can not change the parent class of the original function. In other words: When a subclass inherits the parent class, in addition to adding new methods to complete the new features, but try not to override the parent class method.    If a new function is accomplished by a method overrides the parent class, write up is simple, but relatively poor reusability will inherit the entire system, especially the use of multi-state more frequently, run error probability will be very large .

3) Dependency Inversion Principle

Origin: Dependency Inversion Principle (Dependence Inversion Principle, DIP) • Robert Martin (Robert C.Martin) Object Mentor's president in 1996 in C ++ published in the Report article. 
   Dependency Inversion Principle is defined as the original: High module should not rely on low-level modules, both of which should rely on its abstract; abstract should not rely on the details, the details should depend on the abstract. The core idea is: to be oriented programming interface, do not realize oriented programming.
The reason: Since the software design, the details have variability, and the abstraction layer is relatively stable, so abstract as the basis to build up infrastructure than to build up the basis of the details of the architecture is much more stable. Herein it refers to the abstract interface or an abstract class,
   and refers to details of a specific category. The purpose of using an interface or abstract class is to develop a good standard and contract, not to involve any specific action, the task to show the details of their implementation classes to complete.
Action: . A Dependency Inversion Principle can reduce the coupling between classes. B. Dependency Inversion Principle can improve system stability. C. Dependency Inversion principle can reduce the risk caused by the parallel development. . D Dependency Inversion Principle code readability and maintainability can be improved
implementation: Dependency Inversion Principle object is to reduce the coupling between classes through the programming interface to face A of each class or abstract class provides the interface as possible. or both are available. B. Declared type variable as far as possible an interface or an abstract class. C. Any type should not be derived from the specific class. D. Try to follow the Richter substitution principle when using inheritance.

 4) Single Responsibility Principle

Origin: Single Responsibility Principle (Single Responsibility Principle, SRP), also known as single responsibility principle, by Robert • C Martin (Robert C. Martin) in. "Agile Software Development: Principles, Patterns and Practice," a book 
   put forward. Responsibility here is the reason for the change of class, single responsibility principles laid a class should have one and only one cause why it changes, otherwise the class should be split.
Contrary to the principle cause of the disadvantage: 
   . A change could weaken a duty or inhibit the ability of this class implements other duties; 
   B when a client needs a certain duties of the object, will have to include all other unwanted responsibilities. come in, resulting in a waste of redundant code or code. 

Advantages: The core particle size is controlled like the principle of a single responsibility, decouple objects, to improve the cohesion. If you follow the single responsibility principle will have the following advantages. 
   A. Reduce complexity class. A class is only responsible for a duty, certainly better than its logic is responsible for a number of duties is much simpler. 
   B. Improve the readability of the class. Reduce complexity, increase natural readability. 
   C. To improve the maintainability of the system. Improve readability, it is much easier to maintain. 
   D. Change risk reduction caused. Change is inevitable, if the single responsibility principle comply well, when modifying a function, you can significantly reduce the impact on other functions. 
Method:   single principle role is the most simple but difficult to use the principle functions necessary to design different classes found and isolated, and then encapsulated into different classes or modules. The class found various responsibilities require designers to have strong analytical skills and design-related
  reconstruction experience.

5) Interface Segregation Principle

Origin: 2002 Nian • C Robert Martin definition of "Interface Segregation Principle" is: The client should not be forced to rely on methods that do not use (Clients Should not BE ON Forced to the depend Methods They do not use) 
   . This principle has another definition: a class dependent on another class should be based on the smallest interface. Two meanings defined above are: To establish a dedicated interface they need for each class, rather than trying to build a very large interface
   for all classes that depend on it to call.
Definition: The Interface Segregation Principle (Interface Segregation Principle, ISP) require the programmer to try to split the bloated interface into smaller and more specific interface that allows interface methods contain only interested customers.
And the interface segregation principle distinction single responsibility:    Interface Principles and isolating single responsibility is to improve the cohesion and the like, to reduce the coupling between them, embodies the idea of the package, but they are different:    A single principle functions. pay attention to the duty, and the interface segregation principle focus is to isolate the interface dependent.    . B single responsibility principle mainly bound class, which is a program for the implementation and details; primary constraint interfaces Interface Isolation principle, primarily built for the overall program and abstract framework.
Advantages:    . A bloated interface will be broken down into multiple small size interface, it can prevent the spread of exotic change, improve flexibility, and maintainability.      project to bring    B. Interface Isolation improved cohesion of the system, reducing the external interaction, reducing the coupling system.    . C If the particle size of the interface definition of reasonable, to ensure the stability of the system; however, if the definition is too small, it will cause excessive number of interfaces, complicating the design; If the definition is too large, reduce flexibility, unable to provide customized services , to the overall
unforeseen risks.
   D. Using multiple specialized interface also can reflect the level of objects, because it can through inheritance interfaces, to achieve the overall definition of the interface. 
   E. Can reduce code redundancy project engineering. Interface oversized large number of methods which are usually placed not in use, when the implementation of this interface, forced to design redundant code. 
Implementation:    . A interfaces as small as possible, but there's a limit. An interface dedicated to a single submodule or business logic.    B. Is dependent interface class customized services. Only the caller needs to provide a method of shielding unwanted method.    C. Understand the environment, refused to follow blindly. Each project or product has selected environmental factors, different environments, different split of a standard interface to understand the business logic.    D. Improve cohesion and reduce the external interaction. The interfaces with the least method to accomplish most things.

6) Demeter

Origin: Demeter (Law of Demeter, LoD) also called the principle of least knowledge (Least Knowledge Principle, LKP), generates a Northeastern University named to the United States in 1987 (Northeastern University)

   Demeter (Demeter) research project, presented by Ian Holland (Ian Holland), was Butch (Booch) the popularity of one of the founders of UML, and later because of the classic "The Pragmatic Programmer" (The Pragmatic

   Programmer) mentioned and well known.

 

Definition: only talk directly with your friends, not with "strangers" talk (Talk only to your immediate friends and not to strangers). The implication is: if two software entities without direct communication, then there should be

   The occurrence of a direct call each other, the call can be forwarded through a third party. The aim is to reduce the coupling between classes, increasing the relative independence of modules. Demeter in the "friend" means: the current object itself, members of the current object of the current

   Objects created object, object parameters, the current method, the presence of these objects is associated with the current object, or a combination of relationships polymerization, you can directly access the objects.

 

Advantages: restrict communication between software entities required width and depth of

   A. Reducing the coupling between the classes, increases the relative independence of the module.

   B. Since the affinity degree is reduced, thereby improving the scalability of the system and the multiplexing rate classes.

 

Disadvantages: the excessive use of the system will generate a lot of Demeter intermediary class, thereby increasing the complexity of the system, so reducing the efficiency of communication between modules. Therefore, when the need to weigh preclude the use of Demeter, while ensuring the high cohesion and low coupling,

   Clear structure to ensure system.

 

Implementation:

   A. In the class division, you should create weak coupling type. Coupling between the class and class weaker, the more conducive to achieving the objectives reusable.

   B. In the structural design class, try to reduce access to class members.

   C. In the design class, a priority class is provided to the same class.

   D. In references to other classes, based on the number of references to other objects to a minimum.

   E. Property member of a class is not exposed, but has a corresponding access unit (set and get methods).

   F. Prudent use of serialization (Serializable) function.

 

It is seen from the definition and characteristics of Demeter, which emphasizes the following points:

   A. From the perspective of addicts, it should depend only dependent objects.

   B. From the perspective of the dependence, the method of exposure to be exposed only. 

7) Synthesis of multiplexing principles

Definition: Synthesis of polymerizable multiplexing multiplexing principles (Composition / Principles (Composite Reuse Principle, CRP) known compositions / Aggregate Reuse Reuse Principle, the CARP). It requires a software reuse, to try to use 
   to achieve the association or combination of polymerization, followed before considering the use of inheritance to achieve. If you are using inheritance, we must strictly follow the Richter substitution principle. Synthesis of the complex with the complementary Richter substitution principle with principles, both the opening and closing principle
   is embodied specification.
Common classes into inheritance multiplexing multiplexing and multiplexing two kinds of synthetic, although inheritance multiplexing the advantages of simple and easy to implement, but it also has the following disadvantages:    . A succession multiplexed break encapsulation class. Because the implementation details will inherit the parent class exposed to subclasses, subclasses parent class is transparent, so that multiplexing is also known as "white box" reuse.    B. High child and parent class is coupled. Any changes in the parent class implementation will lead to the realization of a subclass of change, which is not conducive to the expansion and maintenance of class.    C. It limits the flexibility of reuse. Inherit the implementation comes from the parent class is static, defined at compile time, so the change can not happen at runtime. Or using a combination of multiplexing polymerization, there can be incorporated into the new target object, to become part of the new object, the new object can call the function of an existing object, it has the following advantages:    . A package which maintains the class of . Because the internal details of the composition of the object is a new object invisible, so this multiplexing, also known as "black box" reuse.    B. Low coupling between the old and new classes. This multiplexing requires less dependent, a new object is the only way to access the component via the interface component object is an object.    C. High flexibility reuse. This multiplexing can be performed dynamically at run time, a new object may reference the same object type and object component dynamically.
Implementation:    Synthesis of multiplexing principle is by existing objects into the new object, the new object as a member object to achieve, a new object can call the function of an existing object, so as to achieve multiplexing.

。。

 

Guess you like

Origin www.cnblogs.com/bai3535/p/12320359.html