Seven design principles of object-oriented

Source: Internet
Author: User

The following: Mainly describes the seven design principles of the name, definition and frequency of use.

?

Principle One: (Srp:single responsibility principle) Single duty principle also known as single function principle

Core: Decoupling and enhanced cohesion (cohesion poly, low coupling)

Describe:

Classes are much more likely to be modified, so you should focus on a single function. If you put multiple functions in the same class, there is an association between the functions.

Changing one of these features could potentially abort another, requiring a new round of tests to avoid possible problems.

Principle two: Opening and closing principle (Ocp:open Closed Principle)

Core idea: Open to extensions, close for modifications. When designing a module, you should make this model

Blocks can be expanded without being modified.

According to the opening and shutting principle, when designing a software system module (class, method), it should be able to expand its function (extended open) on the basis of not modifying the original module (modify close).

Extended Open:

The function of a module is extensible, then the module is extended and open. The functional scalability of software systems requires that modules be extended and open.

Modify Close:

A module is called by another module, and if the module's source code does not allow modification, the module modifies the shutdown. The functional stability of the software system, the requirement of continuity is the modification.

Principle three: The principle of the Richter replacement (Lsp:liskov Substitution Principle)

Core:

1. Where any parent class appears, it can be substituted with his subclass (subclasses should be able to replace the parent class and appear anywhere the parent class can appear)

Subclasses must fully implement the methods of the parent class. It is important to call other classes in the class to use the parent class or

Port, if the parent class or interface cannot be used, then the design of the class has violated the LSP principle.

2. Subclasses can have their own personalities. Subclasses can of course have their own behavior and appearance, that is, the square

Methods and properties

3. Input parameters can be magnified when overriding or implementing a method of the parent class. That is, the subclass can overload the parent class's methods, but the input parameters should be larger than the parent class method, so that when the subclass is substituted for the parent class, the call is still a method of the parent class. That is, the pre-condition of a method in a subclass must be the same or looser than the predecessor of the method overridden in the superclass.

4. The output can be scaled down when overriding or implementing a method of the parent class.

Principle four: Dependency reversal principle (dip:dependence inversion Principle)

Alias: Dependency inversion principle or dependency reversal principle

Core: To rely on abstraction, do not rely on specific implementations

1. High-level modules should not rely on low-layer modules, both should be dependent on their abstraction (abstract class or interface)

2. Abstraction should not depend on details (concrete implementation)

3. Details (concrete implementations) should be based on abstraction.

Three ways to achieve:

1. Passing a dependent object through a constructor function

2. Passing dependent objects through setter methods

3. Interface Declaration Implementation dependent objects

Principle five: interface separation principle (Isp:interface segregation Principle)

Core idea:

Client programs should not be forced to rely on methods that they do not need to use.

The interface separation principle means that an interface does not need to provide too much behavior, an interface should only provide an external function, and should not encapsulate all operations into an interface.

Two implementation methods for separating interfaces:

1. Detach the interface using a delegate. (Separation through delegation)

2. Detach the interface using multiple inheritance. (Separation through multiple inheritance)

Principle VI: The principle of synthetic multiplexing (Crp:composite reuse Principle)

Core idea:

Try to use object combinations instead of inheritance to achieve reuse. The principle is to use some existing objects within a new object,

Make it part of the new object: New objects are reused for the purpose of the existing functionality by delegating to those objects.

Types of multiplexing:

1. Inheritance

2. Synthetic polymerization

Note: The use of synthetic aggregations rather than inheritance should be a priority when reusing

Principle VII: Dimitri principle (Lod:law of Demeter)

Also called the least knowledge principle

Core idea:

An object should have as little knowledge of other objects as possible and not talk to strangers.

(Decoupling between classes, low coupling) means reducing the coupling between the various objects, improving the maintainability of the system, and communicating only through the interface between the modules,

Regardless of the module's internal operating principle, can make the coupling of each module Chengdu to a minimum, promote the reuse of software

Note:

1. In the Division of classes, a class with weak coupling should be created;

2. In the structure design of the class, each class should minimize the access rights of the members;

3. In the design of the class, whenever possible, a class should be designed to be unchanged;

4. On references to other classes, an object's reference to other objects should be minimized;

5. Minimize the access rights of the class;

6. Use the serialization function with caution;

7. Do not expose class members, but should provide the appropriate accessors (attributes)

UML Unified Modeling Language, seven principles of design in Java

UML Unified Modeling Language.

The relationship between classes and classes, classes and interfaces, interfaces, and interfaces.

1, implementation of the relationship (a class implementation of an interface)

2. Generalization relationship (one class inherits another)

3, association (1), dependency: One class is the method of another class local variable, the method's parameter or method return value. 2), aggregation relationship: One class is the property of another class, and it is the relationship of the whole and the part. 3), combinatorial relationship: One class is the property of another class, is an integral part of the whole, is a strong aggregation. )

4, single duty: A class, there should be only one cause of its change, never let a class there are multiple changes in the rationale. A class should only do business related to a task and should not put too much business into one class.

Dimitri Law:

A software entity should interact with as few interactions as possible with other entities.

?

Summary of seven design principles

Single Responsibility Principle: a class should only do things related to a responsibility, do not put too much business in one class to complete.

Dimitri Law: The minimum interaction between software entities should be achieved. Don't talk to strangers. The caller only cares about the method he needs to use.

Interface Isolation principle: Using a dedicated interface is better than using a unified interface. Facilitate the division of labor, in the implementation of the interface, you should not see the way you do not care.

Open and Close principle: Software entities should be opened to extensions and closed for modification. The opening and closing principle is the core principle of design principle, and the other design principles are the performance and supplement of open and closed principle. The method of realizing open and close principle is abstraction.

Aggregation/combination multiplexing principle. Use aggregations/combinations to achieve code reuse and less inheritance reuse.

Dependency Inversion principle: For abstract programming, do not target specific programming.

Seven design principles of object-oriented

1. Opening and closing principle

2, the Richter replacement principle

3. Single Duty principle

4. Interface Isolation principle

5. Dependency Inversion principle

6. Dimitri Principle

7. Combination/Aggregation multiplexing principle

Knowledge Point Correlation

Learning object-oriented design patterns is the key to deep-object-oriented thinking, and through the subtle cases of masters, we can broaden our awareness.

Before learning the seven principles of object-oriented design, we should have enough knowledge about the basic encapsulation, inheritance and polymorphism, and have enough coding ability for abstract classes and interfaces, because the design pattern is the comprehensive application of the above knowledge points.

In addition, the seven-object-oriented design principles will let you know the inevitability and significance of design patterns before contacting specific design patterns.

1, the precise meaning of each design thought, specific as follows:

First, the overall understanding of the seven design ideas.

First, the opening and shutting principle:

This one is put in the first place to understand that its meaning is open to extensions and closed to modifications. The explanation is that the code we've written is not going to change because of changes in demand. We can address the changing needs in a way that adds code.

Of course, this is an ideal state, in reality, we should try to narrow this change.

To explain the meaning of this principle, we use the reverse way of thinking. If each change in demand to modify the original code, the original code there is the risk of modification errors, of course, there are intentional and unintentional modification, will lead to the original function of the normal operation of the risk of failure, so it is likely to unfold the terrible butterfly effect, so that the maintenance of the work.

In the final analysis, the open and closed principle in addition to the surface of the strong scalability, in the enterprise more value is the maintenance costs.

Therefore, the opening and closing principle is the first principle of design pattern, its subtext is: to control the risk of change in demand, reduce maintenance costs.

There are several principles that serve this principle.

Second, the Richter replacement option:

The implication of this principle is that a subclass can replace its parent class anywhere. To explain this, this is a polymorphic premise, and many of the so-called flexibility behind us is changing the requirements of the instantiation class to complete without changing the declaration type. Of course, inherited traits seem natural enough to satisfy this condition. But this is more about inherited application issues, and we have to ensure that our subclasses and parent classes are accurate.

The subtext of the Richter replacement principle is: Try to use precise abstract classes or interfaces as much as possible.

Iii. single principle of responsibility:

The implication of a single duty is that the class has a single responsibility and causes the class to change for a single reason. Explain, this is also a flexible premise, if we split the class into the smallest functional units, that combination and reuse is much simpler, if a class do too much, in combination, it will inevitably produce unnecessary methods to appear, which is actually a kind of pollution.

For example, when we draw a pattern, we use "dots" to make up a diagram and a "straight line" to make a diagram, which is more flexible? It must be "point", it can draw any shape, and the straight line can only draw a pattern with straight lines, it is at least unable to draw a circle.

The subtext of a single responsibility is to split to the smallest unit and solve the problem of reuse and composition.

Four, the principle of interface isolation:

The principle of interface isolation can be said to be a necessary means of a single duty, meaning to use a single, functional interface rather than a complex, comprehensive interface. It is well understood that the interface is for subclasses to achieve, and if subclasses want to achieve a single function, then the interface must satisfy the single function.

Conversely, if an interface blends multiple unrelated methods, its subclasses are forced to implement all methods, although some methods are not available at all. This is the interface pollution.

The subtext of the interface isolation principle is: Split, starting from the interface.

V. The principle of dependency inversion:

To understand the dependency inversion principle, you must first understand the traditional solution. The initial program of the face object, the caller relies on the caller. That is, the caller decides what method the caller has, what kind of implementation, the structure of the change in demand, will pay a great price, or even overturn rewrite.

The principle of dependency inversion is to require both the caller and the callee to rely on abstraction, so that there is no direct association or contact between the two, and in the case of changes, one party's changes do not affect the other.

In fact, dependency inversion and the previous principles are mutually reinforcing, emphasizing the importance of abstraction.

The subtext of dependency inversion is: For abstract programming, decoupling calls and callee.

Vi. Principles of Dimitri:

The Dimitri principle requires as much encapsulation as possible to be as independent as possible, using low-level access modifiers. This is a typical embodiment of encapsulation characteristics.

A class that exposes too many private methods and fields can leave the caller dazed. and will cause unnecessary judgment code for the class. So, we use the lowest possible access modifier so that the outside world doesn't know about our interior. This is also the basic idea of object-oriented. This is a feature of the Dimitri principle, and it is not possible to understand more private information about classes.

In addition, the Dimitri principle requires the direct contact between classes as little as possible, two classes of access, through the third intermediary class to achieve.

The subtext of Dimitri principle is: Do not talk to strangers, something to intermediary.

VII. combination/Aggregation multiplexing principles:

The implication of this principle is that if you only achieve the purpose of code reuse, use the combination and aggregation instead of inheritance as much as possible. It is to be explained here that combinatorial aggregation simply refers to the methods of other classes, not the inheritance of the referenced classes, and changes the descent.

Inheritance is more coupled, such as a parent class later added to implement an interface or remove an interface, the subclass may be a destructive compilation error, but if it is only a combination of aggregation, only the method of referencing the class, there is no such a huge risk, but also to achieve the reuse.

The subtext of the composite aggregation multiplexing principle is: I'm just using your method, we're not necessarily the same.

2. The following points need to be noted when learning the seven-object-oriented design principles:

A) "conflict" of high cohesion, low coupling and single function

In fact, the two are one thing. Cohesion, requires a class to put all the relevant methods together, the first view is a lot of functions, but there is a "high", is the need to connect very close to the function put together, that is, from the overall view, is a function of the ability to put together, so, the two are different expressions just.

Many people here understand the composite class, but the composite class is not cohesion poly, but the messy put together, is a design error.

b) Flexibility and declarative type issues for multiple single-function interfaces

If a class implements multiple interfaces, which interface type should this class declare? You should use an abstract class to inherit multiple interfaces, and implement classes to inherit this interface. When declaring, a type is an abstract class.

c) The least-knowledge principle and the medium-class flooding of two extreme situations

This is another kind of design mistake. Dimitri principle requires the class to use intermediary to communicate, but after the class is more, it will cause the situation of intermediary class flooding, this situation, we can consider the mediation mode, with a total intermediary class to achieve.

Of course, design patterns have their own flaws, Dimitri principle is not perfect, the interaction of a very wide range of circumstances, to the appropriate sacrifice design principles.

d) "Conflict" in the principles of inheritance and combinatorial aggregation multiplexing

Inheritance can also be reused, is that the principle of abandoning inheritance? No.

Inheritance pays more attention to "descent", which is what type. Combinatorial aggregation is more focused on borrowing "skills". Also, in combinatorial aggregation, two classes are part-to-whole relationships, and combinatorial aggregation can consist of multiple classes of skills. There is only single inheritance in C # and Java.

This principle is not to tell us not to inherit, to use combinatorial aggregation, but at the point of "multiplexing", we prefer to use combinatorial aggregation.

Common problems in object-oriented design principles:

1, so many design patterns, all to learn and use it?

A: We just master the general principles, and then learn the usual on the line. Not every design pattern is often used in real-world development. Because in the final analysis, design patterns, architecture, are all for the needs of service, no need for business model, not mechanically mode. When we learn, it's always good to learn more, but only to broaden our horizons.

2, design mode is the norm? Is good program must use design pattern?

A: Strictly speaking, good procedures follow design principles, not design patterns. Now there are a lot of new models, these are due to the emergence of new business reasons, design patterns are not norms, but a reference.

3, the use of design patterns will increase the difficulty of development?

A: The development phase will be, and will extend the development time. But a project or product from start to finish, development is only a small part of it, considering the maintenance and expansion costs, will appear in the design pattern. As a whole, design patterns reduce development time and costs.

About seven principles of object-oriented design

Object-oriented design principles are one of the important criteria we use to evaluate the effectiveness of a design pattern.

Let me show you what the seven design principles are, and how they are defined:

Single Responsibility principle Definition: A class is responsible for only one area of the corresponding responsibility

Definition of open and closed principle: software entities should be opened for expansion, while for modification

Richter replacement Principle Definition: All objects referencing the base class can transparently use objects of their subclasses

Dependency reversal principle definition: Abstractions should not be dependent on detail, detail dependent on abstraction

Interface Isolation principle Definition: Use multiple specialized interfaces instead of a single total interface

Synthetic reuse Principle Definition: Use object combinations as much as possible instead of inheritance to achieve composite purposes

Dimitri Rule definition: A software entity should interact with as little as possible with other entities

The more commonly used is the red font, blue font only times, the black font is basically not used.

Richter Substitution Principle: The method that the parent class appears, the subclass must be replaceable. If the subclass does not fully implement the parent class method, or if the parent class's method has already distorted in the subclass, then it is necessary to break the parent-child relationship. Replace inheritance with dependencies, aggregations, combinations, and so on. The Richter substitution principle can be used to detect whether two classes have a parent-child relationship.

7 Common Object-oriented design principles

Design Principle Name

Defined

Frequency of Use

Single principle of responsibility

(Single Responsibility Principle, SRP)

A class is responsible only for the corresponding responsibilities in a functional area

★★★★☆

Opening and closing principle

(open-closed Principle, OCP)

Software entities should be open for expansion and closed for modifications

★★★★★

Principle of substitution on the Richter scale

(Liskov Substitution Principle, LSP)

All objects that reference the base class object can transparently use the object of its child class

★★★★★

Dependency reversal principle

(Dependence inversion Principle, DIP)

Abstractions should not be dependent on detail, and details should be dependent on abstraction

★★★★★

Interface Isolation principle

(Interface segregation Principle, ISP)

Use multiple specialized interfaces without using a single total interface

★★☆☆☆

The principle of synthetic multiplexing

(Composite reuse Principle, CRP)

Try to use object combinations instead of inheritance to achieve reuse

★★★★☆

Dimitri Law

(Law of Demeter, LoD)

A software entity should interact with other entities as little as possible

★★★☆☆

Seven design principles of object-oriented

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.