Overview of Design Patterns

Source: Internet
Author: User

1. Design mode

Design patterns are a set of reusable, most known, categorized purposes, code design experience Summary. Design patterns are used in order to reuse code, make code easier for others to understand, and ensure code reliability. There is no doubt that design patterns in others in the system are multi-win, design patterns so that code is truly engineering, design patterns are the cornerstone of software engineering, like a block of bricks and tiles in the building.
Classic definition of Patterns: Each pattern describes a problem that continues to arise in our environment and then describes the core of the solution to the problem, in which we can reuse existing solutions countless times without having to repeat the same work. That is, a pattern is a solution to a problem in a particular environment

2. Design mode purpose

The goal is to teach you how to use real and reliable design to organize your code templates. Simply put, it is from the predecessors in the process of design summary, abstraction of the general good experience.  The main objective is to increase the flexibility and reusability of the program. On the other hand, it also helps to standardize the programming and improve the system development progress.

There is also some advice: do not focus too much on the "design Patterns" of the program. Sometimes it's easier to write a simple algorithm than to introduce a pattern. In most cases, the code should be easy to understand and even cleaner to read. However, in large projects or frameworks, there is no design pattern to organize the code, others are not easy to understand.

A software design model is just a guide. It must be designed according to the programming language and the characteristics and requirements of your application.

3. Design Pattern History

The term "design pattern" was originally designed for the field of architecture. Christopher Alexander in his 1977 book, "A Pattern language:towns/building/construction", which describes some common architectural design problems and explains how to use them, A well-known collection of patterns to start a new and effective design. Alexander's view is well translated into software development, and long-term desirability of using the original components to construct new solutions.

4. Four basic elements of a design pattern

Design patterns make it easier and easier for people to reuse successful designs and architectures. The presentation of proven technologies into design patterns will also make it easier for new system developers to understand their design ideas.

All design patterns have some common features: an identity (a pattern name), a problem statement (a problem statement), and a solution (a solution), effect (Consequences)

pattern Name: The problem, solution, and effect that describes the pattern

The identity of a design pattern (schema name) is important because it allows other programmers to immediately understand the purpose of your code without having to learn in depth (at least through this identity the programmer will be familiar with this pattern). Without this model name, we cannot communicate design ideas and design results with others.

Question (problem): description is a field used to illustrate the application of this pattern.

Describes when the pattern should be used. It explains design problems and the causes and consequences of problems, which may describe specific design problems, such as how to use object representation algorithms. It may also describe a class or object structure that results in an inflexible design. Sometimes the problem section includes a series of prerequisites that the usage pattern must meet.

solution (Solution): describes the execution of this model.
Describes the composition of the design, the relationship between them and their respective responsibilities and ways of collaboration. Because the pattern is like a template that can be applied to many different situations, the solution does not describe a specific and specific design or implementation, but rather provides an abstract description of the design problem and how to solve the problem with a general-meaning combination of elements (class or object combination).

effect (Consequences)

It describes the effect of pattern application and the problem that the usage pattern should weigh. Although we do not always refer to pattern effects when we describe design decisions, they are important for evaluating the costs and benefits of design selection and understanding usage patterns. Most software effects focus on measuring time and space, and they also express language and implementation issues. Because reuse is one of the elements of object-oriented design, pattern effects include its impact on system flexibility, extensibility, or portability, and explicitly listing these effects is useful for understanding and evaluating these patterns. The elaboration of a good design pattern should cover the advantages and disadvantages of using this model.

A pattern is an effective way to solve a particular problem. A design pattern is not a library (a codebase that can be included and used directly in your project), but rather a template (Java bean) to organize your code. In fact, a code base and a design pattern have many different applications.

For example, a shirt you buy from a store is a code base whose color, style, and size are determined by the designer and manufacturer, but it meets your needs. However, if there is nothing in the shop that suits you, you can create your own shirt (design its shape, choose the fabric, and then tailor it together). But if you are not a tailor, you may find it easy to find a suitable pattern and then follow this pattern to design your own shirt. With a model, you can get a skilled design shirt in less time.

Back to the discussion software, a data extraction layer or a CMS (Content management System) is a library-it's been designed and coded, and it's a good choice if it fits exactly what you need. But if you are reading the book design mode, you may find that the inventory (original) solution is not always effective for you. So far you know what you want, and you can achieve it, you just need a model to guide you.

The last idea: like a tailor's model, a design itself is useless. After all, you can't wear a costume model-it's just a piece of thin paper. Similarly, a software design model is just a guide. It must be designed according to the programming language and the characteristics and requirements of your application.

3. Design Pattern Classification1) According to its purpose (pattern is used to do what) can be divided into the creation (creational), structural type (Structural) and behavioral type (behavioral) three kinds:
• The Create pattern is primarily used to create objects.
• Structured mode is primarily used to handle the combination of classes or objects.
• Behavioral patterns are primarily used to describe how classes or objects interact and assign responsibilities.        2) According to the scope, that is, the pattern is mainly used to deal with the relationship between the class and the object, can be divided into class mode and object mode two: • Class pattern: The relationship between the class and subclass, these relationships are established by inheritance, at compile time is determined, is static. • Object mode: Handles relationships between objects, which change at run time and are more dynamic.4. Some basic design patterns (Baidu Encyclopedia) abstract Factory: Provides an interface to create a series of related or interdependent objects without specifying their specific classes.
Adapter(adapter mode): Transforms the interface of one class into another interface that the customer wants. The adapter mode makes it possible for those classes that would otherwise not work together because of incompatible interfaces to work together.  
   Bridge (bridging mode): separates the abstract part from its implementation, so that they can all change independently.
builder(builder mode): separates the construction of a complex object from its representation so that the same build process can create different representations.  
Chain of Responsibility responsibility chain: to decouple the sender and receiver of the request, and allow multiple objects to have the opportunity to process the request. Link the objects together and pass the request along the chain until an object handles it.  
Command mode: Encapsulates a request as an object so that you can parameterize the customer with different requests, queue requests or log requests, and support actions that can be canceled.  
Composite combination mode: Combines objects into a tree structure to represent a "partial-whole" hierarchy. It enables customers to have consistent use of individual objects and composite objects.  
   Decorator Decorator: Dynamically add some extra responsibilities to an object. In terms of extension functionality, it is more flexible than generating subclasses.
facade(appearance mode): Provides a consistent interface for a set of interfaces in a subsystem, and the F a C a D e pattern defines a high-level interface that makes this subsystem easier to use.  
Factory Method Factory methods: Define an interface for creating objects, and let subclasses decide which class to instantiate. The Factory method defers the instantiation of a class to its subclasses.  
Flyweight (enjoy meta mode): Use sharing technology to effectively support a large number of fine-grained objects.
interpreter(interpreter mode): Given a language, defines a representation of its grammar and defines an interpreter that uses that representation to interpret sentences in the language.  
   Iterator iterators: Provides a way to sequentially access individual elements in an aggregated object without exposing the object's internal representation.
Mediator Broker: Encapsulates a series of object interactions with a mediation object. The mediator makes the objects not need to explicitly reference each other, so that they are loosely coupled, and can independently change the interaction between them.  
Memento(Memo mode): captures the internal state of an object without compromising encapsulation, and saves the state outside that object. The object can then be restored to the saved state.  
Observer(Observer mode): Defines a one-to-many dependency between objects so that when the state of an object changes, all objects that depend on it are notified and refreshed automatically.  
Prototype(prototype mode): Specifies the kind of object created with the prototype instance, and creates a new object by copying the prototype.  
   Proxy Mode: Provides a proxy for other objects to control access to this object.
Singleton(singleton mode): guarantees that a class has only one instance and provides a global access point to access it.  
state: Allows an object to change its behavior when its internal state changes. The object appears to have modified the class it belongs to.  
Strategy(Policy mode): Defines a series of algorithms, encapsulates them one by one, and allows them to be replaced by each other. This mode allows the algorithm to be changed independently of the customer using it.  
Template method: Defines the skeleton of an algorithm in an operation, and delays some steps into subclasses. The Template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.
Visitor(visitor mode): represents an operation that acts on elements in an object's structure. It allows you to define new actions that act on these elements without changing the class of each element.   5. Six Principles of design pattern

1) The core principle of the design pattern is :" open - close " principle (open-closedprinciple abbreviation : OCP): open to extensions, close for modifications

Meaning, in a system, for the extension is open, for the modification is closed, a good system is not to modify the source code, you can expand your functionality and realize the opening and closing principle is the key is abstract.

By extending the existing software system, new behaviors can be provided to meet the new requirements of the software, so that the software in change has some adaptability and flexibility. Existing software modules, especially the most important abstraction layer module can not be modified, which makes the software system in the change has some stability and continuity.
In the "open-closed" principle, it is not allowed to modify an abstract class or interface, allowing the extension of a specific implementation class, abstract classes and interfaces play an extremely important role in the "open-close" principle. The need to anticipate possible changes. And anticipate all the extensions that might be known. So "abstraction" here is the key!!!

The closed principle of variability: Find the variable factor of the system and encapsulate it. This is the best implementation of the "open-close" principle. Do not put your variables in multiple classes, or scattered around the program's various corners. You should put the variable factor in the envelope up. and avoid the use of variable factors in the envelope together. The best solution is to block envelopes for your variable factor!! Avoid super large class, Super long class, the appearance of super long Method!! To your program to increase the artistic flavor, the process of art is our goal!!

2) The principle of substitution of the Richter scale: where any base class can occur, subclasses can also appear

Liskov Substitution Principle (Richter substitution principle): Subclasses can have to be able to replace the base class from where it appears. Subclasses can also add behavior based on the base class. This yi is about the relationship between the base class and the subclass, and only when the relationship exists does the Richter substitution principle exist. A square is a classic example of how to understand the principle of substitution on the Richter scale.

3) Dependency reversal principle :: Rely on abstraction instead of relying on specific implementations.

The principle of dependency inversion (dependence inversion Principle) is to rely on abstraction, not on specifics. Simply put, the dependency inversion principle requires the client to rely on abstract coupling. Principle statement:

(1) Abstraction should not be dependent on detail; details should be dependent on abstraction;
(2) to program for the interface, do not program for implementation.

If the principle of opening is the goal, reliance on the reversal principle is the means to reach the "open and close" principle. If the best "open and close" principle is to be achieved, it is necessary to abide by the principle of dependency reversal. It can be said that reliance on reverse principle is the "abstraction" of the best specification!! I personally feel that reliance on the reversal principle is also a supplement to the Richter substitution principle. You understand the principle of the Richter substitution, and it should be easy to understand the dependency reversal principle.

4) synthesis/Aggregation multiplexing principle (CARP): To maximize the use of the composition/aggregation principle rather than the inheritance relationship for software reuse purposes

The synthesis/aggregation multiplexing principle (composite/aggregate reuseprinciple or carp) is often called the synthetic multiplexing principle (Composite reuseprinciple or CRP), which is to use some existing objects in a new object , making it part of the new object, and the new object is being reused for the purpose of the existing functionality by delegating to those objects. In short, use composition/aggregation as much as possible, and do not use inheritance as much as possible.

Use the composition/aggregation principle as much as possible, rather than inheriting relationships to achieve software reuse. This principle and the Richter substitution principle complement each other, both are concrete implementation of the "open-closed" principle of the norms. Violation of this principle: "open-closed" principle can not be achieved. Let's take a look at what is synthesis and what is aggregation.
What is synthesis?
Synthesis: Refers to the relationship that a whole has to rely on him, for example: a person to his house and furniture, wherein his house and furniture can not be shared, because those things are his own. And the man is gone, and this relationship is gone. This example is like, the black chicken Hundred chicken pill This product, it is has the black chicken and the fine medicinal herbs synthesis to come the same. Also like the weapons in the online game, a variety of things merge into a super-strong thing.
What is aggregation?
Aggregation: Aggregation is a stronger dependency than a synthetic relationship, and aggregation is an integral part of the individual, for example, a Mercedes-Benz S360 car, the relationship between Mercedes-Benz S360 engine, Mercedes-Benz S360 tires. These relationships are aggregated in nature. Because Mercedes-Benz S360 engine and Mercedes-Benz S360 tires They can only be used by Mercedes-Benz S360 cars, leaving the Mercedes-Benz S360 car, they lost the meaning of existence. In our design, such a relationship should not occur frequently. This will increase the coupling of the design.
Understanding the synthesis and aggregation relationships, and then to understand the composition/aggregation principles should be clear. To avoid appearing in system design, a class inherits more than 3 times. If so, consider refactoring your code, or redesign the structure. Of course, the best way is to consider the use of synthetic/aggregation principles ...
5) Dimitri Law : classes in the system, try not to interact with other classes, reduce the coupling between classes

The Dimitri rule (law of Demeter or abbreviated LOD) is also called the least knowledge principle (Least knowledge principle or abbreviated to LKP), that is, one object should have as little understanding of other objects as possible.

Other statements: only communicate with your direct friends and don't talk to strangers. A class should know the least about the classes that it needs to be coupled or called, and how complex the internals of your (coupled or called classes) are to me, that's your business, I know the public method you provide, and I'm calling so much that the rest doesn't care.

Dimitri Law and design pattern facade mode, mediator mode make people ignorant

the class in the system, try not to interact with other classes, reduce the coupling between classes, because in your system, you may need to modify these classes, and the relationship between classes and class determines the complexity of the modification, the more interaction, the more difficult to modify, conversely, if the interaction of the smaller, The less difficult it is to modify. For example, Class A relies on Class B, then Class B relies on Class C, and when you modify Class A, you have to consider whether Class B will be affected, and whether the effect of Class B will affect the Class C. If at this time class C again depends on class D, hehe, I think such changes have been affected.
6) Interface Isolation Law : This law is connected to the Dimitri law.

The interface isolation principle (Interface segregation Principle) is that it is better to use multiple specialized interfaces than to use a single total interface. In other words, from the perspective of a customer class, the dependency of one class on another class should be based on the smallest interface.

An overly bloated interface is a pollution to the interface. Customers should not be forced to rely on methods that they do not use.

The Dimitri Law is the purpose, and the interface isolation law is the norm of the Dimitri Law. In order to be as small as possible, we need to use interfaces to standardize classes, and interfaces to constrain classes. To achieve the requirements of Dimitri Law, it is best to implement the interface isolation law, the implementation of interface isolation law, you also meet the Dimitri law ...
6. SummaryThe design pattern is a successful, maintainable reusable design that is summed up from many excellent software systems, and the use of these schemes will prevent us from doing repetitive work and can design high-quality software systems. The main advantages of the design pattern are as follows: 1 The design pattern incorporates the experience of many experts and is used by a wide range of developers in a standard format, providing a common set of design terms and a common language to facilitate communication and communication between developers, making design solutions more understandable.        For developers and designers who use different programming languages, design patterns can be used to communicate system designs, each of which corresponds to a standard solution, and design patterns reduce the complexity of the system for developers to understand. 2) Design patterns make it easier and easier to reuse successful designs and architectures, and presentation of proven technologies into design patterns makes it easier for new system developers to understand their design ideas.        Design patterns make it easier to reuse successful designs and avoid design scenarios that lead to non-reusable designs.        3) design mode makes the design scheme more flexible and easy to modify.        4) The use of design patterns will improve the software system development efficiency and software quality, and to a certain extent, save design costs. 5) Design Patterns help beginners to understand the object-oriented thinking more deeply, on the one hand can help beginners to read and learn the existing class library and other systems in the source code, on the other hand can improve the software design level and code quality.The design pattern is not learned, it is used. To learn the design patterns, the effect may not be very good. The general framework uses design patterns. such as the PHP ZF used in many design patterns, the framework of the class name or directory name, the name of a design pattern, so that when you see the class name or file name, we know its code structure. If proficient in the language, the rest of the code is very simple, with the accumulation of coding experience, the more thorough understanding of design patterns and principles, the process is the mountain poor water Vista, and results. also need to pay attention to, after the proficiency mode, do not because of mode two go mode. If, as the famous mathematician Hua talked about the three realms of Reading, said, "Reading is from thin to thick, and then from thick to thin process." It means that you have practiced your home.

Overview of Design Patterns

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.