Principles of design patterns proposed by Bertrand Meyer

Source: Internet
Author: User

【Abstract]The principle of the design pattern is that the module should be open to expansion, but the modification should be closed. The module should try not to modify the original ("original", which refers to the originalCode) Code. So how can we expand? Let's look at the factory model "factory pattern": Suppose Zhongguancun has a hacker who sells pirated disk and wool film. We designed a "CD sales management software" for him ".

Why should we use the design model? Why are so many design patterns designed? Why do we advocate "Design Pattern? The root cause is to reuse code and increase maintainability. So how can we achieve code reuse? OO has seven principles of its predecessors: "open-closed" principle (open closed principal), Rishi replacement principle, merging and Reuse Principle, dependency reversal principle, interface isolation principle, abstract class, dimit law. The design pattern is to achieve these principles, so as to achieve code reuse and increase maintainability.

1. "Open-Close" Principle

One of the cornerstones of these Ood principles is the open-closed principle (open-closed principle OCP ). this principle was first proposed by Bertrand Meyer. the original English text is: software entities shocould be open for extension, but closed for modification. it means that a software entity should be open to extensions and closed to modifications. that is to say, when designing a module, we should enable the module to be extended without being modified.Source codeTo change the behavior of this module.

Satisfying the OCP design brings two unparalleled advantages to the system.

1. By extending existing software systems, new behaviors can be provided to meet new demands for software and make the changed software systems adaptive and flexible.

2. The existing software modules, especially the most important abstract layer modules, cannot be modified any more, which makes the software system in change stable and continuous.

The software system with these two advantages is a system that achieves reuse at a high level and is easy to maintain. So how can we achieve this principle? It cannot be modified but can be extended. This seems self-contradictory. in fact, this can be done. According to the object-oriented statement, this means that the abstract layer of the system cannot be changed, but the Implementation Layer of the system can be expanded.

The key to solving the problem lies in abstraction. we allow the module to depend on a fixed abstract body so that it cannot be modified. At the same time, we can extend the behavior function of this module by deriving from this abstract body. so, this designProgramYou can only add code to change the existing code, instead of modifying the existing code. The side effects of the modification mentioned above will no longer exist.

If the "open-close" principle is described from another perspective, it is the so-called "principle of encapsulation of variation, EVP ). it is about finding a variable factor in a system and encapsulating it. when we think about a system, we should not focus on what will lead to design changes, but on what changes will be allowed rather than making the changes lead to redesign. that is to say, we must actively face changes and actively tolerate changes, rather than evading them.

2. Lee's replacement principle

Describes how to build an extends (inheritance, derivation) structure.
The relationship between the subclass and its parent class must be is-a, that is, the subclass must dare to declare itself at least (at least) as a parent class in any situation. For example, in a certain structure, "Man" and "woman" are derived from "man" and seem to satisfy the principle of "Li" replacement, because no matter "man" or "woman ", it is a "person" on any occasion ". In most cases, this principle can be considered using concepts in the real world, but the software world is different from the display world. For example, in the book, the question of "whether a square is a rectangle" is true.
In addition, many questions need to be considered flexibly using the OO core idea. It is also an example in the book (I only mean it, it may be different from the description in the book), a class structure, "Employees, general employees, project managers, section chiefs, ministers ......", Derived from the "employee" class, the general concept is not bad. both employees and ministers are employees, but the hidden problem is that in the real world, ordinary employees may become project managers, however, in the software world, general employees and project managers are planned to be two classes, so it is difficult for a general employee instance to become a Project Manager instance, this shows that we have a problem ing the display world into the software world. A more reasonable approach is to abstract these roles, such as interfaces/abstract classes, from which all roles are derived, the employees and positions are associated. Every employee instance has a job instance as its attribute. In this way, the positions of employees can be changed. The basis for implementing this reconstruction is the encapsulation change idea in Oo, the dependency switching principle evolved from it, and the synthesis/aggregation Reuse Principle.
However, all design patterns involving the extends structure comply with the Lee's replacement principle:
Rule mode: A groupAlgorithmEncapsulate them into objects to make them interchangeable (the same interface is met, that is, the is-a interface ).
Merging mode: leaf and composite are both-a component, so it is possible to easily nest layers.
Proxy mode: both proxy and realsubject are-a parent class subject, so you can insert a proxy to complete the additional function.

3. Principles of merging and reuse

Synthesis and aggregation are special types of association. Aggregation indicates the "ownership" relationship or the relationship between the whole and the part, while merging indicates a strong "ownership ". In a compositing relationship, the partial and overall life cycles are the same. A new merged object is completely used and the right to control other components. Including their creation and destruction. The combined object has absolute responsibility for memory allocation and memory release of the components. For more information, see. A compositing object cannot have more than 1. In other words, some objects in a compositing relationship cannot be shared with other compositing objects.
Synthesis is generally understood as the aggregation of values. Aggregation is the reference aggregation.
Merging and aggregation are to include existing objects into new objects and make them part of new objects. Therefore, new objects can call functions of existing objects. Achieve the purpose of reuse.

Advantages:

L the only way for a new object to access a component object is through the component object interface.

This reuse method is black box reuse, which hides the internal details of component objects.

This type of reuse supports packaging.

This reuse dependency is small. (Low coupling)

Each new class can focus on a task.

This type of multiplexing can be performed dynamically at runtime. The new object can dynamically Reference Sub-objects of the component object type.

Disadvantages:

Systems built through this reuse usually have a large number of objects to manage.

"Merging aggregation reuse can replace inheritance reuse to complete any function ."

4. Dependency reversal Principle

It provides detailed guidance on the use of abstract classes (interfaces) and implementation classes.
Dependent on abstract entities (interface/abstract class ), (any implementation class instance that implements the existing interface can be inserted to the interface instance role where the interface is dependent ), it is easier to meet the open-close principle (Abstract layers do not change and implementation layers use different classes to encapsulate different changes, so you can add new classes as extensions without modifying existing implementation classes ).

5 interface isolation principles

Meaning: it is better to use multiple special interfaces than to use a single total interface!
From the perspective of customer class: the dependence of a class on another class should be built on the smallest interface.
The division of interfaces directly leads to the division of types.
The goal is not to provide unnecessary behaviors to the customer class.

6 abstract classes

The abstract class does not have instances. It is generally inherited as a Child class of the parent class and generally contains the common attributes and methods of this series.

Note: In a good inheritance relationship, only leaf nodes are specific classes, and other nodes should be abstract classes, that is, specific classes

Is not inherited. Put as much common code as possible into the abstract class.

7 dumit's Law

Used to unlock unnecessary coupling between classes. "Do not talk to strangers ". It is easy to say that, in actual operations, there may be some at-risk problems, and it is important to solve the coupling between classes. At present, when we design classes, adding attributes and calling other classes are not good.
The DEMETER rule requires that an object should have as little knowledge as possible about other objects. Several other statements: only communicate with your friends directly, and do not talk to strangers (Feng yuanzheng ?)
Each software organization has the minimum knowledge of other units and is limited to software units closely related to the same unit.
The DEMETER rule in a narrow sense specifies who is friends and who is stranger. Friends Circles include:
The current object itself (this), instance field (if the field is a map, list, and other container types, the objects in the container are also friends), the object created by the current object (call its constructor) parameter object of the current object method.
Only talk to friends, And the words spoken to stranger are described by friends.
Disadvantages of the Demeter rule in a narrow sense: too many small methods are passed for indirect calls! Solution: Follow the dependency switching principle to make some trade-offs so that the object is dependent on the stranger abstraction layer. Although the coupling is not completely disconnected, at least the coupling is reduced.

conclusion: in a software system, the most important and important sign of a module's design is the extent to which the module hides its internal data and other implementation details. A Designed module can hide all its implementation details, API is separated from your own implementations. In this way, modules communicate with each other only through API . This is: "hiding information" .

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.