Software Design Patterns

Source: Internet
Author: User

Utilizing design Patterns

A metaphor for design patterns

Martial arts routines are the gateway to martial Arts. Novice to a recruit a style to practice routines, after the heart, make perfect, in the actual combat is visible recruit demolition recruit, freely--at this time the people have been from the "novice" to grow into a "hand." "Master" There is no routine, the actual combat only natural reaction , but a recruit a style, just right, seems to have no, nothing. "Master" on top of the "High Master", they reached the realm of not me and so on by virtue of the Jin's martial arts fiction can be speculated.

Design patterns are designed to be like routines for martial Arts. "Novice" to a one-to-one learning mode, "good players" can utilize the mode, "master" is no mode.

The "Internal strength " of design pattern is the basic principle of object-oriented. These principles are " God " and the pattern is " form ". Master spell is "internal strength", the basic principles of the object of a profound understanding, to use a good design mode, to avoid "the obsession."

In general, the first few chapters of the design pattern work introduce the basic principles of object-oriented, and these chapters are very important. Learn to pass these chapters, the back of the model is no more than that. After learning the design pattern, it is also better to turn over to look at these chapters, to ensure that there will be a new understanding.

Second, why use design patterns

Any design can be judged by the subjective (difficult to make an objective evaluation of the design) to determine whether it is a good design, or a bad design. Design patterns are used to avoid bad designs. Uncle Martin describes the symptoms of poor design in his book Agile Software development Principles, patterns and practices:

L rigidity (rigidity): design is difficult to change.

L Vulnerability (fragility): design is easily compromised.

L Robustness (immobility): Design is difficult to reuse.

L Viscosity (Viscosity): Difficult to do the right thing.

L Unnecessary complexity (needless complexity): excessive design.

L Unnecessary repetition (needless repetition): excessive repetition.

L obscure (Opacity): the expression of confusion.

Iii. when to use design patterns

There was a passage in Uncle Martin's book:

As you learn them (design principles and patterns), keep in mind that agile developers do not apply those principles and patterns to a large, pre-engineered design. Instead, these principles and patterns are applied over and over again, trying to keep the code and the design that the code is expressing clean.

In this text which is easy to be ignored by the reader, I realize the meanings of these layers:

L code is a design (This is an idea that Uncle Martin emphasizes, which can be referenced in Appendix D to the principles, patterns and practices of agile software development);

L design pattern is to adapt the design to change;

L design pattern is the tool of reconstruction;

L design should be kept clean and simple at the beginning, and still keep clean and simple in the future.

L cannot overuse design patterns.

The purpose of using design patterns is to adapt to future changes , and change exists because of its unpredictability--if predictable, it cannot be called a change. It is a process problem, not an engineering one, to determine which requirements are likely to change, which requirements are likely to be the same, and to keep the design clean and simple for the most part. Since it is a process problem, then we can only give the principle, can not give the standard. The general principle of using design patterns might be to give the simplest, least-cost solution to a problem that is likely to change in the future.

Iv. avoid excessive use of design patterns

Easy -to-maintain procedures are first and foremost understandable, much more than others. easy to understand code to maintain. The excessive use of design patterns increases the complexity and ambiguity of the program, making the program difficult to understand and thus reducing the ease of maintenance of the program.

Switch statements have been criticized, and many of the refactoring examples are the use of switch surgery. I think the switch statement is an efficient statement that can write extremely elegant, simple code. In many cases, using a switch statement directly is more "clean" than splitting it into several classes.

For example, there is a section of more than 400 lines of code responsible for the entire system scheduling, if the future change is only to modify the 400 lines of code and not add a lot of code, then put the 400 lines of code in a function, more than split it into a few 10 classes easier to maintain.

V. Discussion of several specific models

1. Creation mode (creational pattern)

The Factory mode (Factory method) is a common pattern. The application of Factory mode is clear and the design idea is simple. From using polymorphism to just one static method, there are many variations in the factory pattern. I'm used to simply using the Factory mode, which is the Factory mode with only static methods. The following Factory mode code is simple and clean:

Myfactory.getclassinstance (). Dofunction ();

The class factory does not carry the business logic, and the impact of demand changes on the plant is usually very small. So using heavy-weight factory models is often not a good deal. A set of heavyweight factory classes that contain hierarchical relationships can mean over-design.

The singleton mode (Singleton Method) is closely related to the factory model. From the implementation point of view, the singleton mode is a special case of the factory pattern, but the two patterns of the application scenarios are different, so they belong to different patterns.

Abstract Factory mode (FactoryMethod) is the promotion of Factory mode. Abstract Factory mode application scenarios are more specific and rigorous. In a design that uses abstract factories, the abstract factory model may collapse if the different product families evolve in the future. In the actual application, the different product family each evolution, finally parted the situation is some, the user proposed such demand really lets the person "shocking". Before using the abstract factory model, it is important to ensure that these product families are used in a consistent manner from now to in the future.

The construction mode can be obtained by changing the Factory mode slightly. The "machining process" of the factory model is hidden , while the "processing process" of the construction mode is exposed . This is different, making the construction model more flexible while also losing grace.

2. Template mode and Policy mode (strategy method)

Template patterns and policy patterns are similar in application scenarios, but are implemented in different ways, using inheritance and the latter using delegates .

template mode is probably one of the most "old" patterns, and in the early days of using object-oriented technology, "inheritance" is a great way to go, and many designers may unconsciously use template patterns. The disadvantage of template mode is that the concrete implementation and the general algorithm are tightly coupled, so that the concrete implementation can only be manipulated by a general algorithm. However, in an inheritance relationship, the information of the parent class can be exposed more to subclasses, and this subtle communication (contrary to object-oriented design principles) is more flexible and convenient in some specific applications.

The policy pattern is the classic use of delegates . The strategy mode eliminates the coupling between the general algorithm and the concrete implementation, so that the concrete implementation can be manipulated by several general algorithms. The policy model also adds class hierarchies , which are more complex than template patterns.

Template patterns and policy patterns can often be replaced with each other. They are like test papers, template mode is the blank question , the strategy mode is the choice problem .

3. Model for simplifying problems

The façade mode (Façade method) hides a complex set of interfaces behind a simple and specific interface.

The Mediator mode (mediator method) wraps the reference relationship between objects in a specific container.

The combined mode (Composite method) describes the structural relationship of the whole and the part, and allows the structure to be handled in a consistent manner.

The above models have played a part in simplifying the problem to the user.

4. Extended function mode

Both the visitor mode (Visitor method) and the adornment mode (Decorator method) can dynamically add functionality without altering the existing class structure.

The visitor pattern assigns an object on an existing class structure to a class called a visitor, configures the object, alters the object, or extends functionality in the appropriate method of the visitor.

decoration mode " injects " an object from an existing class structure into an ornamental class, extending its functionality in the adornment class.

The visitor pattern and the adornment mode are different in actual effect. The visitor pattern can be used to assign objects to the corresponding methods, thus processing or expanding each object separately . The decorative mode can only be used in a consistent manner to all the decorative objects are processed or expanded , in order to achieve different processing or expansion, can only add new decoration class.

Too many "adornment classes" may cause the business logic to disperse and complicate the program structure. For each specific derived class, the "Access class" must have a corresponding method, adding the derived class should also increase the way to access the class. The need for extended functionality is frequent, and it is worthwhile to consider the use of the above pattern.

5. Other common patterns

Bridge Mode (Bridges method). Class is a container that encapsulates behavior and attributes, whereas a class's set of behaviors can evolve independently, and the most straightforward idea is to use inheritance to encapsulate different behaviors in separate subclasses. Bridge mode solves this problem from a different angle. The bridge mode encapsulates the independent evolution behavior in another class system, and evolves independently from the original class system, and the two-class system is the "use" relationship at the level of abstraction. In many OO textbooks, the shape class encapsulates attributes and draw methods, and in bridge mode, "shapes" and "brushes" are two groups of independent evolutionary classes, at the level of abstraction, "shape" paints itself with "brushes".

Adapter Mode (Adapter method) is a common pattern, it is relatively simple, and sometimes used in conjunction with other modes.

Command mode is known by Martin as "one of the simplest and most elegant modes". The charm of the command pattern is that it has the same skills for each class "training", and that the "training" class "Flex" is stronger and can produce incredible abilities.

6. Less-needed patterns

Viewer Mode (Observer method). Both Java and C # Implement the Observer pattern.

Iterative sub-mode (Iterator method). In the Java and C # languages, you can use aggregation classes instead.

Memo Mode (Memento method). Can be replaced with the serialization capability of class.

Responsibility Chain Mode (Chain of Responsibilitymethod). Can be substituted in other ways, such as the observer pattern, the message mechanism provided by the language itself, and so on.

The interpreter mode (Interpreter method). Personally think that it is an algorithm, not a pattern.

Agent Mode (proxy method). If you know from the beginning that certain underlying policies are bound to be replaced, it is still necessary to use proxies to isolate these policies. Otherwise, there is little need to use it.

Reference documents:

1.Gamma etc., designpatterns:elements of reusable object-oriented software. addison-wesley1995. (Chinese translation: Design mode: The basis of reusable object-oriented software, Li Yingjun, etc., mechanical industry Press, 2000)

2.Robert C. Martin,agile softwaredevelopment Principles, Patterns, and practices. (Chinese translation: Principles, patterns and practices of agile Software Development, Aaron Translation, Tsinghua University Press, 2003)

Yu Zhang has worked in the Wave group, Lenovo Group, is currently working in the CAS Electronics Institute. More than 10 years experience in software work. Has a strong interest in analysis design, project management, programming practice.

--------------------------------------------------------------

Reference:

"tlee--design Mode"

"Yyyuhan--c++ design Mode"

"maobisheng--design Mode"

"Pluginsin C + +"

"Buildinga Better Plugin Architecture (c + +)"

"Buildingyour Own Plugin Framework"

Software 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.