Big Talk Design Pattern 1: The five basic principles of the initial knowledge design pattern and design pattern

Source: Internet
Author: User

What is design mode?

Design patterns are a set of reusable, most known, categorized purposes, code design experience Summary. Use design

Patterns are designed to reuse code, make code easier for others to understand, and ensure code reliability. There is no doubt that design patterns are more in the system than others

Win; Design patterns make code compilation truly engineering; Design patterns are the cornerstone of software engineering, like the structure of a building.

Two Why should I use design mode?

Why should we advocate design pattern? The root cause is for code reuse, which increases maintainability. So how do you implement code reuse? Surface

there are several principles to the object: Single responsiblity Principle SRP, Open Closed PRINCIPLE,OCP,

Richter Substitution principle (Liskov Substitution principle,lsp), dependency reversal principle (Dependency inversion Principle,DIP), interface isolation

principles (Interface segregation principle,isp), synthesis/aggregation multiplexing principles (composite/aggregate reuse Principle,carp), the most

The principle of small knowledge (Principle of Least Knowledge,plk, also known as the Dimitri Law). The open and close principle has the idealistic color, it is object-oriented

The ultimate goal of design. The other several, can be regarded as the opening and closing principle of the implementation method.

The design pattern is the realization of these principles, so as to achieve code reuse, increase maintainability.

Five basic principles of three design patterns

Before learning to design patterns, it is first clear that the pattern is for object-oriented, its three main features, encapsulation, inheritance, polymorphism. Object-oriented design patterns have

5 Basic principles: Single duty principle, open and close principle, dependency inversion principle, interface isolation principle, Richter substitution principle. The design patterns we learn are

Based on the object-oriented characteristics and the 5 basic principles, it is necessary to introduce the basic concepts of several major principles before learning.

(1) Single duty principle (SRP)

1SRP Definition: In the case of a class, there should be only one cause for it to change. In short, it is a single function.

2 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 completion of this class.

The ability to perform other duties. This coupling leads to fragile designs that can be subjected to unexpected damage when the changes occur. (Agile Software Development)

3 Software Design The real thing to do is to discover responsibilities and separate those responsibilities from each other. (Agile Software Development)

4 The principle of single responsibility can be regarded as the extension of low coupling, cohesion in object-oriented principle, and defines responsibility as the cause of change, in order to improve the internal

To reduce the cause of the change. The more responsibilities that may cause it to change, this leads to a reliance on responsibility that creates

Due to the large damage to the cohesion and coupling degree.

5 whether in the design class, the interface or the method, a single responsibility will be everywhere, the definition of a single responsibility: we define the responsibility as the system changes in the original

Because All at the time of defining classes, interfaces, methods. After the definition is finished, think about it, there is no more than one motive to change this class, interface, method.

If the answer is yes, the description defines the class, interface, and method with more than one responsibility. Contrary to a single duty, this situation should be re-subdivided

Classes, interface methods (discovering responsibilities and separating those responsibilities from each other) until there are no more responsibilities. Single duty for the simplest of five original

is one. In the process of software design is reflected everywhere. Everywhere.

(2) opening and closing principle (OCP)

definition of 1OCP: This means that software entities (classes, methods, and so on) should be extensible, but cannot be modified. It is also the most important one in software design.

Design principles.

Two characteristics of 2OCP:

A is open for extensions.

B is closed for modification.

3 When should I apply the OCP principle?

When we first wrote the code, we assumed that the changes would not occur, and when the changes occurred, we created abstractions (such as abstract classes, interfaces, and so on) to isolate

Similar changes occur after the

4 The opening and closing principle is the core of object-oriented design. Following this principle can lead to the great benefits claimed by object-oriented technology, which is the dimension

Can be extended, reusable and flexible. Developers should abstract only those parts of the program that exhibit frequent changes, however, for application

It is also not a good idea to deliberately abstract each part of the sequence. Rejecting immature abstractions is as important as abstraction itself.

5 The open and closed principle means that classes, modules, methods can be extended, but not modified. Open to expansion, closed to modify the closed. Opening and closing principle

Applications now, developers should simply abstract (encapsulate the point of change) where changes occur frequently in the program. The encapsulation of the change point is the modification of the change

Switch off. The uncertainty of change can be extended at any time. That is, the use of inheritance. The use of abstract classes.

UML diagram for 6OCP:

(3) Richter replacement principle (LSP)

definition of 1LSP: subtypes must be able to replace their parent types. Simply put, this is because the subtype inherits the parent class, so subclasses can

Parent the identity of the class appears.

2 where any base class can appear, subclasses must be able to appear. LSP is the cornerstone of inheritance reuse, and only if the derived class can replace the base class, the software

When the function of a unit is not affected, the base class is actually reused, and the derived class can add new behavior on the base class. The principle of substitution on the Richter scale

The opening and closing principle complements. The key step of implementing the open and close principle is abstraction. And the inheritance relationship between the base class and subclass is the concrete implementation of abstraction, so the Richter

The substitution principle is the specification of concrete steps to achieve abstraction.

3 implementation of the substitution principle. For a group of classes that have similar properties, methods, and variables. We can extract public properties, methods, variables as a base

class (abstract class or Class), which causes this set of classes to inherit the base class, overriding the virtual method. Now the relationships of these inherited classes and base classes conform to is-a. If the base class is an animal, then

following Bearing classes can be for dogs, cats. We can say that cats is-a animals, dogs is-a animals.

4 Example UML diagram:

Java code to implement:

Animal parent class class animal{public void Eat () {} public    void Drink () {} public void    run () {} public    void Shout () {}}//cat Subclass class Cat extends Animal{}//dog subclass class Dog extends Animal{}//cattle subclass class Cattle extends Animal{}//sheep subclass CL Sheep extends Animal{}public class test{public static void Main (string[] arge) {Animal Animal = new Cat ();//depending on the requirements, this can be To replace the dog,cattle or sheep, the program does not need to change the       () elsewhere;                Animal.drink ();       ();                Animal.shout ();}}

5 Summary: All places where subclasses are used in a project can be replaced by the parent class, but when the method is called, the object-oriented programming polymorphism is rendered. That

The principle of the replacement of the Richter scale, very important principle, is also a more difficult principle.

(4) Dependency inversion principle (DIP)

definition of 1DIP: Abstractions should not be dependent on details, and details should be dependent on abstraction. High-level modules should not be dependent on low-layer modules, both of which should rely on

Abstract. Simply put, we want to program for the interface, not for the implementation.

2 Inverse Example UML diagram:

Cons: High-rise modules are too dependent on low-level modules and are too tightly coupled. Changes in the low-level modules can affect high-layer modules.

Workaround: Use the dependency inversion principle to make both the high-level and lower-layer modules dependent on abstractions (interfaces or abstract classes).

The revised UML diagram is as follows:

Advantage: In this way, modifying the lower layer module will not affect the high-level module, reduce the coupling between them, enhance the stability of the system.

3 in the process-oriented development language analysis and design, always create a number of high-level modules to invoke the low-layer module, policy-dependent software structure of the details.

In fact, the purpose of this method is to define the subroutine hierarchy, which describes how the high-level module calls the lower-layer module. And the well-designed oriented

Like the program, just "upside down" this dependency of high-level module, block no longer rely on low-level modules, so that the modification of low-layer module does not affect the high-rise module,

and high-level modules can be easily reused, both the high-level modules and the lower-layer modules are dependent on abstraction. This also fits well with the strong cohesive loosely coupled

Programming ideas. Therefore, this principle is also the core principle of frame design.

With the dependency structure created by the traditional procedural programming, the policy is dependent on the details, which is bad because it makes the policy

Subject to changes in detail, object-oriented programming inverts the dependency structure, and the entire detail and strategy are dependent on abstraction and are often client programs

Owns the service interface. In fact, the inversion of this dependency is the hallmark of good object-oriented design, and the language used to write programs is irrelevant.

It's going to be. If the dependencies of a program are inverted, it is an object-oriented design. If the dependencies of the program are not inverted, it is a process-based


The 4 dependency inversion principle is a basic low-level mechanism for realizing the benefits claimed by many object-oriented technologies. Its correct application is to create a reusable framework to

Said to be necessary. It is also important for building code that is resilient in the face of change, because abstractions and details are isolated from each other, so the code is not

Often easy to maintain.

5 Summary: The dependency inversion principle can be said to be the object-oriented design of the logo, in which language to write the program is not important, if the writing is considered

is a How to Program for abstract programming, not for detail, that is, all the dependencies in the program The relationship is terminated by an abstract class or interface, which is an object-oriented

Set It's a process design. .

(5) interface Isolation principle (ISP)

definition of 1ISP: Examples of custom services, each interface should be a role, not a lot, do not do things, should do the work.

2 using multiple dedicated interfaces is better than using a single total interface. The dependency of a class on another class should be based on the smallest interface.

An interface represents a role, and different roles should not be handed over to an interface. Interfaces that are not related merge together to form a bloated big connection

interface, which is a pollution to the roles and interfaces. Customers should not be forced to rely on methods that they do not use. The interface belongs to the customer and does not belong to the class hierarchy where it resides.

Frame. This is very clear, and then more popular, do not force customers to use their methods, if forcing users to use the method they do not use, it

These customers will face changes due to these non-use methods.

3 It should be said that the principle is to deal with the shortcomings of the existing "fat" interface. If the interface of a class is not cohesive, it means that the class has a "fat" interface. In other words

Say "fat" interfaces can be decomposed into multiple groups of methods. Each group of methods serves a different set of client programs. In this way, the volume draw client program can use a group of members

function, while other client programs can use the member functions of other groups.

There are two ways to isolate a 4 interface (sharing a customer is a separate interface):

A uses a delegate (this delegate is not a. NET delegate [delegate]) to detach the interface.

Use a delegate to create a delegate class that implements the methods in the other interfaces after separation.

b Use multiple inheritance to detach the interface,

This method, the existing "fat" interface is divided into two or more interfaces for different client programs, and needs to implement multiple interfaces of the client program, then the

Implemented with multiple inheritance. These two methods are the whole method of implementing interface isolation, the second method is more common and simpler to use. And the first kind of party

method is relatively complex to use, and also produces duplicate objects in the process of using delegates, which consumes runtime and memory overhead. Sometimes the first

Two methods are required and the first method is not available. Such as: Conversions made with a delegate object are required, or different times will be required

The conversion.

Four reviews

(1) Object-oriented final design goals:

a scalability: with new requirements, new performance can easily be added to the system without compromising existing performance or bringing new flaws.

B Flexibility: Adding new functionality code changes to occur smoothly without affecting other parts.

C Replaceable: You can replace some code in the system with other classes of the same interface, without affecting the system.

(2) Benefits of Design Patterns:

A design pattern enables people to reuse successful designs and architectures more easily and conveniently.

B Design Patterns will also make it easier for new system developers to understand their design ideas.

(3) The Learning design pattern has a triple realm (seen several times online):

First: You learn a design pattern and think about where I can use it in my new project (with a knife in my hand and no knife in my heart)

Second Weight: design mode you are finished, but when you encounter a problem, you find that there are several design patterns for you to choose from, you have nowhere to go (hand

There is a knife in the heart, there is a knife)

The third heavy: is also the last weight, you may not have the concept of design mode, the heart only a few major design principles, etc.

The highest state: no knife in hand, no knife in the heart

Big Talk Design Pattern 1: The five basic principles of the initial knowledge design pattern and 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: 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.