Some Basic Design Patterns

Source: Internet
Author: User
Edit some basic design patterns in this section

Abstract Factory: provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes.

Adapter: converts an interface of a class to another interface that the customer wants. The A d a p t e r mode makes those classes that cannot work together due to interface incompatibility work together.

Bridge: separates abstract parts from their implementations so that they can all change independently.

Builder: separates the construction of a complex object from its representation, so that different representations can be created during the same construction process.

Chain of responsibility: to cancel the coupling between the request sender and receiver, multiple objects have the opportunity to process the request. Connect these objects into a chain and pass the request along the chain until an object processes it.

Command: encapsulate a request as an object so that you can parameterize the customer with different requests, queue requests or record request logs, and support cancelable operations.

Composite: combines objects into a tree structure to represent a "part-whole" hierarchy. It makes the customer's use of a single object and composite object consistent.

Decorator: dynamically add some additional responsibilities to an object. The extended function is more flexible than the subclass generation method.

Facade: provides a consistent interface for a group of interfaces in the subsystem. The f a c a d e mode defines a high-level interface, which makes the subsystem easier to use.

Factory method: defines an interface for creating objects, so that the subclass determines which class to instantiate. Factory method delays the instantiation of a class to its subclass.

Flyweight: uses the sharing technology to effectively support a large number of fine-grained objects.

Interpreter: for a given language, define a representation of its syntax and define an interpreter that uses this representation to interpret sentences in the language.

Iterator: provides a method to access each element of an aggregate object sequentially without exposing the internal representation of the object.

Mediator: uses an intermediary object to encapsulate a series of object interactions. The intermediary makes the objects do not need to be explicitly referenced to each other, so that the coupling is loose and the interaction between them can be changed independently.

Memento: capture the internal state of an object without compromising encapsulation, and save the state outside the object. In this way, the object can be restored to the Saved state.

Observer: defines a one-to-many dependency between objects, so that when the status of an object changes, all objects dependent on it are notified and automatically refreshed.

Prototype: Use a prototype instance to specify the type of the object to be created, and copy the prototype to create a new object.

Proxy: provides a proxy for other objects to control access to this object.

Singleton: ensures 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 seems to have modified its class.

Strategy: defines a series of algorithms, encapsulates them one by one, and makes them replaceable. This mode makes the algorithm changes independent of the customers who use it.

Template Method: defines the skeleton of an algorithm in an operation, and delays some steps to the subclass. The template method allows the subclass to redefine certain steps of an algorithm without changing the structure of an algorithm.

Visitor: an operation that acts on each element in an object structure. It allows you to define new operations that act on these elements without changing the classes of each element.

Detailed description

Each of the following design patterns is described in detail starting from the next section.

Creation type Structural Behavior Type

Class factory method adapter_class Interpreter

Template Method

Object Abstract Factory

Builder

Prototype

Singleton adapter_object

Bridge

Composite

Decorator

Facade

Flyweight

Proxy chain of responsibility

Command

Iterator

Mediator

Memento

Observer

State

Strategy

Visitor

Overview

Factory method

Structure

The intent defines an interface for creating objects, so that the subclass determines which class to instantiate. Factory method delays the instantiation of a class to its subclass.

Applicability when a class does not know the class of the object it must create.

When a class wants its subclass to specify the object it creates.

When a class delegates the responsibility of creating an object to one of multiple help sub-classes, and you want to localize the information of which help sub-classes are proxies.

Abstract Factory

Structure

The intent is to provide an interface for creating a series of related or mutually dependent objects without specifying their specific classes.

Applicability a system is independent of the creation, combination, and representation of its products.

A system must be configured by one of multiple product generations.

When you want to emphasize the design of a series of related product objects for joint use.

When you provide a product class library, instead of displaying their interfaces.

Builder

Structure

The intention is to separate the construction of a complex object from its representation so that different representations can be created during the same construction process.

Applicability when creating complex objects, algorithms should be independent of the components of the objects and their assembly methods.

When the constructor must allow different representations of the constructed object.

Prototype

Structure

The intent is to use the prototype instance to specify the type of the object to be created, and create a new object by copying the prototype.

Applicability when the class to be instantiated is specified at the runtime, for example, through dynamic loading; or

To avoid creating a factory class level parallel to the product class level; or

When an instance of a class can only have one of several combinations of different States. Creating prototype and cloning them may be more convenient than manually instantiating this type with the appropriate state each time.

Singleton

Structure

The intent is to ensure that a class has only one instance and provide a global access point to it.

Applicability when a class can only have one instance and the customer can access it from a well-known access point.

When this unique instance should be extensible through subclass, and the customer should be able to use an extended instance without changing the code.

Adapter

Structure

It is intended to convert the interface of a class into another interface that the customer wants. The A d a p t e r mode makes those classes that cannot work together due to interface incompatibility work together.

Applicability you want to use an existing class, and its interface does not meet your needs.

You want to create a reusable class that can work together with other unrelated classes or unforeseen classes (that is, classes whose interfaces may not be compatible.

(Only applicable to object a d a p t e r) You want to use existing subclasses, but it is impossible to subclass each of them to match their interfaces. The Object Adapter can adapt to its parent class interface.

Bridge

Structure

The intent is to separate the abstract part from its implementation part so that they can all change independently.

Applicability you do not want to have a fixed binding relationship between the abstraction and its implementation. For example, this may be because the implementation part of the program should be selected or switched during the runtime.

Class abstraction and its implementation should be expanded by generating sub-classes. In this case, the B r I d G E mode allows you to combine different abstract interfaces and implementation parts and expand them separately.

The modification of an abstract implementation part should not affect the customer, that is, the customer's Code does not need to be re-compiled.

(C ++) You want to completely hide the abstract implementation part of the customer. In C ++, the class representation is visible in the class interface.

There are many classes to generate. Such a hierarchical structure indicates that an object must be divided into two parts. R u m B A u g h refers to this type of hierarchy as "nested generalization" (nested generalizations ).

You want to share the implementation among multiple objects (the reference count may be used), but the customer is not required to know this. A simple example is c o p l I e n s t r I N G class [c o p 9 2], multiple objects in this class can share the same string representation (s t r I n g r e p ).

Composite

Structure

It is intended to combine objects into a tree structure to represent the "part-whole" hierarchy. C o m p o s I t e makes the use of a single object and a composite object consistent.

Applicability: the part of the object-the overall hierarchy.

You want to ignore the differences between a composite object and a single object. You will use all objects in the composite structure in a unified manner.

Decorator

Structure

Intention to dynamically add some additional responsibilities to an object. With the added function, the d e c o r a t o r mode is more flexible than the subclass generation mode.

Applicability adds responsibilities to a single object dynamically and transparently without affecting other objects.

Handle unrecoverable responsibilities.

When the subclass generation method cannot be used for expansion. One case is that there may be a large number of independent extensions. To support each combination, a large number of subclasses will be generated, resulting in explosive growth of the number of subclasses. Another scenario is that the class definition is hidden, or the class definition cannot be used to generate a subclass.

Facade

Structure

The intent is to provide a consistent interface for a group of interfaces in the subsystem. The f a c a d e mode defines a high-level interface, which makes the subsystem easier to use.

Applicability when you want to provide a simple interface for a complex subsystem. Subsystems tend to become more and more complex as they evolve. In most modes, More and smaller classes are generated. This makes subsystems more reusable and easier to customize, but it also brings some difficulties for users who do not need to customize subsystems. F a c a d e can provide a simple default view, which is sufficient for most users, those who need more customization can go beyond the f a c a d e layer.

There is a large dependency between the implementation part of the client program and the abstract class. Introducing f a c a d e to separate the sub-system from the customer and other sub-systems can improve the independence and portability of the sub-system.

When you need to build a layered sub-system, use the f a c a d e mode to define the entry points for each layer of the sub-system. If subsystems are mutually dependent, you can allow them to communicate only through f a c a d e, thus simplifying the dependency between them.

Flyweight

Structure

Intention to use the sharing technology to effectively support a large number of fine-grained objects.

Applicability an application uses a large number of objects.

Because a large number of objects are used, the storage overhead is very high.

Most States of an object can be changed to external states.

If you delete the external state of an object, you can replace multiple groups of objects with a relatively small number of shared objects.

Applications do not rely on object identifiers. Because the f l y w e I g h t object can be shared, the logo test returns the true value for an object that is conceptually distinct.

Proxy

Structure

The intent is to provide a proxy for other objects to control access to this object.

Applicability when we need to replace simple pointers with common and complex object pointers, we use the p r o x y mode. The following are some common scenarios where the p r o x y mode can be used:

1) remote proxy provides a local representation of an object in different address spaces. Nextstep [add94] uses the N x p r o x y class to achieve this goal. Coplien [cop92] calls this proxy "Ambassador" (a m B A s a d o r ).

2) virtual proxy creates objects with high overhead as needed. The I m a G E P R o x y described in the motivation section is an example of such a proxy.

3) protection proxy controls access to the original object. Protection proxy is used when the object should have different access permissions. For example, in the C h o I c e s operating system [c I r m 9 3], k e m e l p r o x I e s provides access protection for operating system objects.

4) Smart reference replaces simple pointers and performs some additional operations when accessing objects. Its typical uses include:

The reference count pointing to the actual object. When this object is not referenced, it can be automatically released (also known as s m a r tp o I n t E R S [E d e 9 2]).

When a persistent object is referenced for the first time, it is loaded into the memory.

Before accessing an actual object, check whether it is locked to ensure that other objects cannot change it.

Chain of responsibility

Structure

The intention gives multiple objects the opportunity to process the request, thus avoiding the coupling relationship between the request sender and the receiver. Connect these objects into a chain and pass the request along the chain until an object processes it.

Applicability there are multiple objects that can process a request, and the object that processes the request is automatically determined at the runtime.

You want to submit a request to one of multiple objects without specifying the receiver explicitly.

The object set that can process a request should be dynamically specified.

Command

Structure

The intent is to encapsulate a request as an object so that you can parameterize the customer with different requests, queue requests or record request logs, and support unrecoverable operations.

The applicability is like the m e n u I t E M object discussed above, abstracting the action to be executed to parameterize an object. You can use the callback (c a l B A C K) function in the process language to express this parameterization mechanism. A callback function is a function that is registered at a certain place and will be called at a later time. The c o m a n d mode is an object-oriented alternative to the callback mechanism.

Specify, arrange, and execute requests at different times. A c o m a n d object can have a lifetime unrelated to the initial request. If the recipient of a request can be expressed in a way unrelated to the address space, the command object responsible for the request can be sent to another different process and implemented there.

Cancel the operation. The c o m a n d e x c u t e operation can store the status before performing the operation. This status is used to eliminate the impact of the operation when the operation is canceled. The c o m a n d interface must add a u n e x e c u t e operation, which cancels the effect of the last e x e c u t e call. The executed command is stored in a history list. You can traverse this list backward and forward and call u n e x e c u t e and redo ".

Logs can be modified so that the modifications can be redone when the system crashes. Add the loading and storage operations to the c o m a n d interface to maintain a consistent change log. Recovery from a crash involves re-reading the recorded commands from the disk and re-executing them with the e x e c u t e operation.

Construct a system with high-level operations built on primitive operations. Such a structure is common in information systems that support transactions (t r a n s a c t I o n. A transaction encapsulates a group of changes to the data. The c o m a n d mode provides a method for modeling transactions. C o m a n d has a common interface that allows you to call all transactions in the same way. At the same time, it is easy to add new transactions to expand the system.

Interpreter

Structure

The intent is to give a language, define a representation of its syntax, and define an interpreter that uses this representation to interpret sentences in the language.

Applicability when a language needs to be interpreted and executed, and you can represent sentences in the language as an abstract syntax tree, you can use the interpreter mode. This mode works best in the following situations:

This grammar is simple for complex grammar, and the class layers of grammar become huge and cannot be managed. At this time, the syntax analysis program generator is a better tool. They can interpret expressions without building an abstract syntax tree, which saves space and time.

Efficiency is not a key issue. The most efficient interpreter is usually not implemented by directly interpreting the syntax analysis tree. Instead, they are first converted into another form. For example, regular expressions are usually converted to state machines. However, even in this case, the converter can still be implemented in interpreter mode, which is still useful.

Iterator

Structure

The intent provides a way to access each element in an aggregate object sequentially without exposing the internal representation of the object.

Applicability accesses the content of an aggregate object without exposing its internal representation.

Supports multiple traversal of aggregate objects.

Provides a unified interface (supporting multi-state iteration) for Traversing different aggregation structures ).

Mediator

Structure

It is intended to encapsulate a series of object interactions with an intermediary object. The intermediary makes the objects do not need to be explicitly referenced to each other, so that the coupling is loose and the interaction between them can be changed independently.

Applicability a group of objects communicate in a well-defined but complex manner. The resulting dependency structure is confusing and hard to understand.

An object references many other objects and communicates directly with these objects, making it difficult to reuse the object.

We want to customize a behavior distributed in multiple classes without generating too many child classes.

Memento

Structure

The intention is to capture the internal state of an object without damaging encapsulation, and save the state outside the object. In this way, the object can be restored to the previously saved state.

Applicability must save the (partial) state of an object at a certain time point so that it can be restored to the previous state later.

If an interface is used to directly obtain these States for other objects, the implementation details of the object will be exposed and the object encapsulation will be broken.

Observer

Structure

The intent defines a one-to-many dependency between objects. When the State of an object changes, all objects dependent on it are notified and automatically updated.

Applicability when an abstract model has two aspects, one of which depends on the other. Encapsulate the two in independent objects so that they can be changed and reused independently.

When changing an object, you need to change other objects at the same time without knowing how many objects need to be changed.

When an object must notify other objects, it cannot assume who the other objects are. In other words, you do not want these objects to be tightly coupled.

State

Structure

The intention is to allow an object to change its behavior when its internal state changes. The object seems to have modified its class.

APPLICABILITY The behavior of an object depends on its state, and it must change its behavior according to its state at runtime.

An operation contains a large number of conditional statements with multiple branches, and these branches depend on the state of the object. This state is usually represented by one or more enumerated constants. Generally, multiple operations contain the same condition structure. In the s t a t e mode, each condition branch is placed into an independent class. This allows you to take the object state as an object based on the object's own situation. This object can be independent of other objects.

Strategy

Structure

Intent defines a series of algorithms, encapsulate them one by one, and make them replaceable. This mode allows algorithms to change independently of customers who use it.

Applicability many related classes only have different behaviors. "Policy" provides a method to configure a class with one of multiple actions.

Different variants of an algorithm are required. For example, you may define algorithms that reflect different space/time trade-offs. When these variants are implemented as class layers of an algorithm [h o 8 7], the policy mode can be used.

Algorithms use data that customers should not know. Policy modes can be used to avoid exposing complex algorithm-related data structures.

A class defines multiple behaviors, and these behaviors appear in the form of multiple conditional statements in the operations of this class. Move related condition branches into their respective s t r a t e g y classes to replace these condition statements.

Template Method

Structure

The intent defines the skeleton of the algorithm in an operation, and delays some steps to the subclass. Te m p l a t e m e t h o d allows the subclass to redefine certain steps of the Algorithm without changing the structure of an algorithm.

Applicability: implement the unchanged part of an algorithm at one time, and leave the variable behavior to the subclass for implementation.

Common behaviors in each subclass should be extracted and concentrated into a common parent class to avoid code duplication. This is a good example [o j 9 3] of "redecomposition to generalization" described by o p d y k e and J o h n s o n. First, identify the differences in the existing code and separate the differences into new operations. Finally, replace these different codes with a template method that calls these new operations.

Control subclass extension. The template method only calls the "h o k" operation at a specific point (see effect), so that the extension can only be performed at these points.

Visitor

Structure

Indicates an operation that acts on each element in an object structure. It allows you to define new operations that act on these elements without changing the classes of each element.

Applicability an object structure contains many class objects with different interfaces, and you want to perform operations on these objects dependent on their specific classes.

You need to perform many different and unrelated operations on the objects in an object structure, and you want to avoid causing these operations to "pollute" the classes of these objects. Vi S I t o r allows you to set relevant operations in a class. When the object structure is shared by many applications, use the vi S I t o r mode to allow each application to only include the operations needed.

Classes that define the object structure are rarely changed, but new operations are often needed in this structure. Changing the object structure class requires redefining the interfaces for all visitors, which may be costly. If the object structure class changes frequently, it may be better to define these operations in these classes.

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.