Some design principles in the design pattern

Source: Internet
Author: User
Tags to domain

Seven Famous design principles

1. Single Duty principle (Srp-single Responsibility Principle)
As far as a class is concerned, there should be only one cause for it to change, with a single function
If a class takes on too much responsibility, it is tantamount to coupling these responsibilities, and a change in responsibility may weaken or inhibit the ability of the class to perform other duties, which can lead to a fragile design that will suffer unexpected damage when the change occurs.

The real thing about software design is to discover responsibilities and separate those responsibilities from each other, and if you can think of more than one motive to change a class, then this class has more than one responsibility.

2. Open-Close principle (Ocp-open Closed Principle)
Is that software entities (classes, modules, functions, and so on) should be extensible, but not modifiable
is open for extensions and is closed for changes
Allows the system to continuously launch new versions after the first version

No matter how ' closed ' the module is, there are changes that cannot be closed, and since it is not possible to completely close the design, the designer must make a choice about which change the design pattern should be closed, and he must first guess what kind of change is most likely to occur and then construct an abstraction to isolate those changes.

By the time the changes occur, when we first write the code, we assume that the changes do not occur, and when the changes occur, we create abstractions to isolate the similar changes that occur later.

In the face of demand, changes to the program are made by adding new code instead of changing the existing code

What we want is to be aware of possible changes in the development process shortly, and the longer it takes to identify possible changes, the more difficult it is to create the right abstraction.

We should abstract only those parts of the program that are showing frequent changes, but it is also not a good idea to deliberately abstract each part of the application. Rejecting immature abstractions is as important as abstraction itself.

3. Dependency reversal principle (dip-dependency inversion Principle)

High-level modules should not rely on low-layer modules, two should be dependent on the abstract
Abstraction should not depend on detail, details should depend on abstraction, i.e. interface-oriented programming, not programming

In fact, who do not rely on who, in addition to the agreed interface, we can be flexible
Dependency reversal can be said to be object-oriented design flags, in which language programming is not important, if you are writing to consider how to program for abstract programming rather than the details of the program, that is, all the dependencies of the application is terminated in the abstract class or interface

4. Lee's replacement principle (Lsp-liskov Substitution Principle)
Simply put, subtypes must be able to replace their parent type
A software entity if you use a parent class, then it must apply to its subclasses and it does not recognize the difference between the parent and subclass objects, that is, in the software, the parent class is replaced by this subclass, the behavior of the program does not change

Only when a subclass can replace the parent class, the functionality of the Software Unit is not affected, the parent class is actually exploited, and the subclass can add new behavior on the basis of the parent class

Because the substitution of subtypes makes it possible to extend a module that uses a parent class type without modification

5. Dimitri Law (Lod-law of Demeter) (minimum knowledge principle)
If two classes do not have to communicate directly with each other, then these two classes should not have a direct interaction, if one of the classes needs to invoke a method of another class, you can forward the call through a third party

In the structure design of a class, each class should minimize the access rights of members
The fundamental idea is to emphasize the loose coupling between classes, the weaker the coupling between classes, the more beneficial the reuse, the more a weakly coupled class is modified, and does not affect the related classes.

6. Synthesis/polymerization multiplexing principle (carp-composite/aggregate reuse Principle)
Aggregates existing objects into new objects, making them members of new objects, thereby achieving reuse by manipulating these objects
Compositing is more loosely coupled than inheritance, so it should be less inherited, more aggregated

Composition (composition) and aggregation are all special kinds of associations, and aggregation represents a weak ' owning ' relationship, which shows that a object can contain a B object, but B object is not part of a object; the composition is a strong ' own ' relationship, which embodies the strict part and the whole relationship, part and the whole life cycle.

The advantage is that taking precedence over the composition/aggregation of objects will help you keep each class encapsulated and focused on a single task so that classes and inheritance levels remain small and unlikely to grow into uncontrollable behemoths

7. Interface Isolation principle (Isp-interface segregation Principle)
Client programs should not be forced to rely on methods that they do not use
Try to apply a dedicated interface rather than a single total interface, the interface should be user-oriented and rely on the smallest interface
This also implements a single principle of responsibility, a class that only does something specific, not everything.

Design principles in the GRASP model


grasp is the point of view of object-oriented design, which tells us how to design the class in the problem space and their responsibility, and the relationship between the classes and so on.

general Responsibility Assignment Software patterns
General responsibility Assignment software mode
Core idea:
" Responsibility Assignment (Responsibility Assignment) "
Design objects with Responsibilities: "Designing Objects with Responsibilities"

> do your own thing. (Assignment of duties)
> do your own thing. (Assignment of duties)

Five basic modes
1, Information Specialist (information expert)
2, Creator (Creator)
3, high cohesion (high Cohesion)
4, Low coupling (lo coupling)
5, controllers (Controller)
Four expansion modes
6, polymorphism (polymorphism)
7, purely fictitious (pure fabrication)
8, indirect (indirection)
9, prevent mutation (Protected variations)

---Information expert (Information expert)

The most basic pattern of solving the class's responsibility assignment problem in grasp mode.

Problem:
What is the principle of allocation of responsibilities (which objects will be assigned to execute) after we have discovered the objects and responsibilities for the system?

Solution:
The execution of duties requires certain information (information), assigning responsibilities to the owner of the information. In other words, the execution of a duty requires certain resources, and only the object that owns those resources is eligible to perform the duties. -"The one who can do it"
It satisfies the design of the encapsulation of object-oriented design, and usually satisfies the information expert mode. Because information Expert is an encapsulation of the properties (information) of a class and the operation of a class's properties, it conforms to the concept of object encapsulation.

Advantages:
-The owner class of the information is also the operator class of the information, which reduces the association between unnecessary classes.
-All types of responsibilities are single and clear, easy to understand


---creator (Creator)

Grasp mode solves the problem of creating responsibilities for instances of classes.

Problem:
What classes should be assigned to the creation responsibility of the instance of the class? Or who should an instance of a class be created by?

Solution:
When one of the following conditions is true, the creation responsibility for instances of Class A is assigned to Class B. 1,b contains a2,b aggregation a3,b records a4,b frequent use of a5,b with a initialization data
Advocating an instance of a class (object) creation responsibility is created by the object that aggregates or contains the object

Advantages:
-The whole structure is clear and understandable
-Facilitates reuse of classes or components
-Prevention of decentralization of duties
-Reduction of coupling

---high cohesion (high Cohesion)

In grasp mode, the principle pattern of object-oriented design is proposed in order to reduce the complexity of class and simplify the control. The high cohesion (high Cohesion) and low-coupling (lower coupling) modes are fundamental to grasp other modes.

Problem:
What can be done to reduce the complexity of the class and simplify control?

Solution:
Tightly related functions (responsibilities) should be assigned to the same class. --"duties"
The so-called cohesion, refers to a single object (class) of the internal function aggregation degree. For example, a class that contains only interrelated functions, has high cohesion, and its external representation (action, intent) is also obvious; conversely, if a class is composed of some unrelated functions, its cohesion is low, its external performance is not obvious, on the one hand it is difficult to understand its role and intentions, on the other hand, once the demand changes , the extensibility is poor.

Advantages:
-Aggregation of relevant functions, clear structure, easy to understand
-only aggregate related functions, so that the responsibilities of the class are single clear, thus reducing the complexity of the class, using simple

---low coupling (coupling)

In grasp mode, the principle pattern of object-oriented design is proposed in order to reduce the complexity of class and simplify the control. The high cohesion (high Cohesion) and low-coupling (lower coupling) modes are fundamental to grasp other modes.

Problem:
What can be done to reduce the degree of association between classes, can adapt to changes in demand?

Solution:
When assigning responsibilities to classes, you should minimize the association between classes (coupling). That is, the principle of assigning responsibilities should be reduced by reducing the coupling relationship between classes.
The so-called coupling refers to the degree of physical or mean correlation between multiple objects (classes). In object-oriented methods, the class is the most basic element, and the coupling mainly refers to the degree of correlation between different classes. An object-oriented association refers to a class's invocation of another class, aggregation (inclusion), parameter passing, and so on. For example, the so-called 2 closely related classes (high coupling) are when one of the classes changes (modified), and the other class has to be changed (modified).
Object-oriented design requires that the "low coupling" principle be met between classes, which is an important criterion for measuring the quality of a design, because "low coupling" helps minimize the impact of changes in one part of the system on other parts.

Advantages:
1, on the one hand, high cohesion requires that the tightly related functions (responsibilities) be clustered in the same class, preventing the proliferation of functions and the unnecessary increase of classes, thus reducing the association between classes and reducing the chance of coupling between classes.
2, on the other hand, high cohesion requires that unrelated functions be dispersed to different classes, and the class increases, inevitably resulting in an increase in the number of interconnected classes, thus increasing the probability of coupling between classes.

---controllers (Controller)

The pattern in grasp mode that resolves the issue of event handling responsibilities.

Problem:
In addition to the UI layer, which class should handle (control) system operations (events)? Or, when triggering a system event, you should assign the handling responsibility of the event to a class outside the UI layer.

Solution:
Assign the processing responsibility of the system event to the controller class.
The controller pattern advocates the use of a specialized class to handle all system events. or the controller mode assigns the processing responsibility of all system events to a specialized class-focused processing.

Advantages:
-To prevent the dispersion of similar duties. Satisfies the principle of high cohesion and low coupling.
-Facilitates common treatment (pre-treatment, post-treatment, etc.).
-Highly adaptable to change. Be able to control the change range within the minimum range (Controller).

---polymorphism (polymorphism)

Problem:
How do I handle type-based selection? How do I create pluggable software artifacts?

Solution:
When the related selection or behavior varies with the type (Class), a polymorphic operation is used to assign responsibilities to the changed behavior type.

---indirection (indirection)

Problem:
How do you assign responsibilities in order to avoid direct coupling between two or more things? How can I decouple objects to support low coupling and provide the potential for reuse?

Solution:
Assign responsibilities to mediation objects and avoid direct coupling between them. The intermediary realizes the indirect nature.
A large number of gof modes, such as adapters, skins, etc., are the embodiment of indirection.


---pure fiction (fabrication)

Problem:
When you do not want to violate high cohesion and low-coupling or other goals, but what are the objects that should assume this responsibility if the scheme provided by the expert model is not appropriate? (In many cases, assigning responsibilities to domain objects can lead to poor cohesion or coupling, or reduced multiplexing potential)

Solution:
Assigning a set of high cohesion responsibilities to a man-made class does not represent the concept of a problem domain-fictitious things that support cohesion clustering, low coupling, and multiplexing.
All Gof design Patterns (or other modes) are purely fictitious.

---prevent mutation (Protected variations)

Problem:
How can objects, subsystems, and systems be designed so that their internal changes or instabilities do not adversely affect other elements?

Solution:
Identify expected changes or instabilities and assign responsibilities to create a stable interface outside these changes.
Almost all software or architecture design techniques are exceptions to prevent mutation, such as encapsulation, polymorphism, interfaces, virtual machines, configuration files, etc.


The core mechanism of preventing mutation

1. Data-driven Design (Data-driven):
prevent data, metadata, or explanatory variables from affecting the system by externally, reading, and judging change factors.
2. Service Lookup:
A special case of data-driven design, such as Jndi,uddi, allows customers to avoid the impact of service location changes by using a stable interface for query services.
3. Interpreter-driven Design (Interpreter-driven):
The system avoids the effects of logic changes by external, read, and interpret logic.
4, reflective or meta-level design (reflective or meta-level):
avoids the effects of changes in logic or external code
5. Unified Access (Uniform access):
such as the xxx.name in C #
6. Standard language (Language)
7. Liskov Replacement principle (LSP):
in cases where there is any substitution implementation for t or a subclass (becoming s), a reference to the software (method, class ...) of type T (an interface or abstract superclass). Should work normally or as expected.
8. The law of Demeter:
do not experience long-distance object structure paths to send messages to indirect objects far away.
9. Open-closed principle (OCP):
modules should be open and closed (for changes that affect customers) at the same time (for expansion, adaptability).

---grasp software development model-Summary

Grasp and Gof are known as software development models, and only describe different content and angles.
Grasp and GOF are different types of patterns, starting from different. Grasp is how to solve the interaction between classes, how to design reasonable, and the specific problem is irrelevant.

Gof often solves specific problems, such as how classes are created and so on, and grasp is the basic principle of solving object analysis, that is, how you design the classes in your problem space and their behavior, which are principled things.

GRASP is suitable for object analysis and design, that is, in the RUP production analysis model and design model stage, GOF is more suitable for the actual coding process as a more specific guiding ideology

Some design principles in the design pattern

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.