Design mode mode Adapter (Adapter) excerpt

Source: Internet
Author: User

23 seed Gof Design patterns are generally divided into three categories: the creation mode, the structure model, the behavior pattern.

Creating instances of schema abstraction, they help to build a system that is independent of how, and which is a combination of these objects and statements. Creates an instance of a class schema change using inheritance, and the establishment of an object type model will delegate the instantiation of an object.

The main theme of the broken appearance. First, they encapsulate the information about which detailed classes the system uses.

Second. They hide how instances of these classes are created and put together. What the whole system knows about these objects is the interfaces defined by the abstract classes.

Thus, creating a pattern gives very great flexibility in what is created, who creates it, how it is created, and when it is created. They agree to configure a system with "product" objects that differ very much in structure and function. The configuration can be static (that is, specified at compile time), or it can be dynamic (at execution time).

Structured patterns involve how classes and objects are combined to get a larger structure.

The structure class pattern adopts the inheritance mechanism to combine interfaces or implementations. A structured object pattern is not a combination of interfaces and implementations, but rather a description of some of the ways in which some objects are combined to achieve new functionality. Because of the ability to change the composition of objects at execution time, object composition is more flexible, and such a mechanism is not possible with static class combinations.

Behavioral patterns involve the allocation of duties between algorithms and objects. Behavior patterns describe not only the patterns of objects or classes. It also describes the communication patterns between them. These patterns depict complex control flows that are difficult to track at execution time.

They shift the user's attention from the control flow to the contact between objects. The behavior class pattern uses the inheritance mechanism to dispatch behavior between classes. The Behavior object pattern uses object compositing instead of inheritance. Some behavioral object pattern descriptions describe how a set of peers can work together to complete a task in which either object cannot be completed alone.

The creation pattern consists of: 1, FactoryMethod (factory method mode), 2, abstract Factory (Factory mode), 3, Singleton (singleton mode). 4, builder (builder mode, generator mode). 5, Prototype (prototype mode).

The structure mode includes : 6, Bridge (bridging mode), 7, Adapter (adapter mode), 8, Decorator (decorative mode), 9, Composite (combination mode), 10, Flyweight (enjoy meta-mode); 11, Facade (appearance mode), 12, Proxy (agent mode).

behavioral patterns include : 13, Templatemethod (template method mode), 14, strategy (strategy mode), 15, State (status mode), 16, OBSERVER (Observer mode), 17, Memento (Memo mode )。 18, Mediator (intermediary mode), 19, command (order mode). 20, Visitor (Interview mode), 21, Chain of Responsibility (responsibility chain mode), 22, Iterator (iterator mode), 23, Interpreter (interpreter mode).

Factory Method: Defines an interface for creating objects, so that subclasses decide which class to instantiate. The Factory method defers the instantiation of a class to its subclasses.

Abstract Factory: Provides an interface to create a series of related or interdependent objects without specifying their detailed classes.

Singleton: Ensure that there is only one instance of a class. and provides a global access point to the interview.

Builder: Separates the construction of a complex object from its representation. Enables the same build process to create different representations.

Prototype: Specifies the kind of object created with the prototype instance, and creates a new object by copying the prototype.

Bridge: Separates the abstract part from its implementation, so that both can change independently.

Adapter: Transforms the interface of a class into another interface that the customer wants. The adapter mode makes it possible for those classes that would otherwise not be able to work together because of incompatible interfaces.

Decorator: Dynamically add some additional responsibilities to an object. In terms of extended functionality, the decorator mode is more flexible than the way the subclass is generated.

Composite: Combines objects into a tree structure to represent a "partial-overall" hierarchy. Composite enables customers to have consistent use of individual objects and composite objects.

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

facade: Provides a consistent interface for a set of interfaces in a subsystem. The facade mode defines a high-level interface that makes this subsystem easier to use.

Proxy: Provides an agent for other objects to control access to this object.

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.

Strategy: Define a series of algorithms, encapsulate them one by one, and make them interchangeable with each other. This mode allows the algorithm to be changed independently of the customer using it.

State: Agrees that an object changes its behavior when its internal states change. The object appears to have changed the class it belongs to.

Observer: 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 on their own initiative.

Memento: Without damaging the encapsulation. captures the internal state of an object and saves the state outside of the object. The object can then be restored to the saved state.

Mediator: Encapsulates a series of object interactions with a mediation object. Intermediaries allow objects to be loosely coupled without having to explicitly cross-reference each other, and can independently change the interaction between them.

Command: Encapsulates a request as an object. This allows you to use different requests to count your customers. Queues or logs request logs for requests, and supports operations that can be canceled.

Visitor: Represents an operation that acts on elements in an object's structure. It enables you to define new actions that act on these elements without changing the class of each element.

Chain of Responsibility: coupling between the sender and receiver of the cancellation request. and allow multiple objects to have the opportunity to handle this request. Link the objects together and pass the request along the chain until an object handles it.

Iterator: Provides a way to access individual elements of an aggregation object in a sequential manner without exposing the object's internal representation.

interpreter: Given a language, defines a representation of its grammar and defines an interpreter that uses that representation to interpret sentences in the language.

Adapter: (1), intention: To convert the interface of a class into another interface that the customer wants.

The adapter mode makes it possible for those classes that would otherwise not be able to work together because of incompatible interfaces.

(2), applicability: A, want to use an existing class, and its interface does not meet your needs. B, want to create a reusable class that can work with other unrelated classes or classes that are not predictable (that is, those that might not necessarily be compatible with the interface); C, (for object adapter only) want to use some already existing subclasses, but it is not possible to subclass each to match their interfaces.

The object adapter is able to adapt its parent class interface.

(3), Precautions: Class adapters use multiple inheritance to match an interface with an interface. Object adapters depend on the combination of objects. class adapters and object adapters have different tradeoffs. Class Adapter: A, match adaptee and Target with a detailed adapter class.

The result is that when we want to match a class and all its subclasses, class adapter will not be able to do the job; B, so that adapter can define adaptee part of the behavior again, because adapter is a subclass of Adaptee; C, only one object is introduced. There is no need for additional pointers to indirectly get adaptee. The object adapter is: A, agree to a adapter with multiple adaptee----that is adaptee itself and all its subclasses (assuming there are subclasses) work at the same time.

Adapter is also able to add functionality to all adaptee at once, and B makes it difficult to redefine the behavior of adaptee. This requires generating a subclass of Adaptee and making adapter reference this subclass instead of referencing Adaptee itself.

(4), some other factors to be considered when using the adapter mode are: A, adapter matching degree: The Adaptee interface and target interface to match the workload of each adapter may not be the same.

The scope of work may be. Transition from a simple interface to supporting a completely different set of operations.

The workload of the adapter depends on how similar the target interface is to the Adaptee interface. B, pluggable adapter: When other classes use a class. Assuming fewer assumptions are required, this class is more reusable.

Assuming that an interface match is built as a class, there is no need to assume that the same interface is visible to other classes. Other words. Interface matching allows us to add our own classes to some existing systems. The interfaces of these systems may be different for this class.

(5), implementing adapter classes using C + +: When implementing an adapter class using C + +. The adapter class should inherit the target class in a public manner. and inherit the Adaptee class in private mode. Therefore, the adapter class should be a subtype of target, but not a adaptee subtype.

(6), correlation mode: Bridge's structure is similar to the object adapter. But bridge mode has a different starting point: Bridge is designed to separate the interface and implementation parts. So that they can be more easy and relatively independent to change.

and adapter means changing the interface of an existing object. Decorator enhances the functionality of other objects and does not change its interface at the same time. Therefore, the decorator-phase application is better transparent than the adapter. The result is that decorator supports recursive combinations, and it is not possible to achieve this purely using adapters. Proxy defines a proxy for an object that does not change its interface.

When both parties are not suitable for changes, they can consider using adapter mode.

The adapter of the class pattern is used to reuse the interface of adaptee in the way of inheritance, while in the adapter of the object pattern, the Adaptee reuse is implemented in a combination way.


Demo Sample Code 1:

#include <iostream>using namespace Std;class target{public:virtual void request () {cout<< "Normal Request" << Endl;}}; Class Adaptee{public:void Specificalrequest () {cout<< "Special Request" <<endl;}}; Class Adapter:public target{private:adaptee* ada;public:virtual void Request () {ada->specificalrequest (); Target::request ();} Adapter () {ada = new adaptee ();} ~adapter () {Delete ada;}};/ /clientint Main () {adapter* Ada = new Adapter (); Ada->request ();d elete Ada;/*result Special request for ordinary request */return 0;}

Demo Sample Code 2:

#include <iostream> #include <string>using namespace Std;class player{protected:string Name;public:player (String strName) {name = StrName;} virtual void Attack () = 0;virtual void Defense () = 0;}; Class Forwards:public Player{public:forwards (String strName): Player (strName) {}public:virtual void Attack () {cout< <name<< "forward attack" &LT;&LT;ENDL;} virtual void Defense () {cout<<name<< "forward defense" <<endl;}}; Class Center:public Player{public:center (String strName): Player (strName) {}public:virtual void Attack () {cout<< name<< "midfield offensive" &LT;&LT;ENDL; virtual void Defense () {cout<<name<< "midfield defense" <<endl;}};/ /For midfield translator class Translater:public player{private:center* Player;public:translater (String strName): Player (strName) { Player = new Center (strName);} virtual void Attack () {player->attack ();} virtual void Defense () {player->defense ();}};/ /clientint Main () {player* p = new Translater ("Xiao Li");p->attack ();/*result small Lee Field offensive */return 0;}

Demo Sample Code 3: Class mode

Adapter.h

#ifndef _adapter_h_#define _adapter_h_class target{public:target (); virtual ~target (); virtual void Request (); Protected:private:};class adaptee{public:adaptee (); ~adaptee (); void Specificrequest ();p Rotected:private:};class Adapter:public Target, Private Adaptee{public:adapter (); ~adapter (); void Request ();p rotected:private:}; #endif//~_ Adapter_h_

Adapter.cpp:

#include "Adapter.h" #include <iostream>target::target () {}target::~target () {}void target::request () {std:: cout<< "Target::request" <<STD::ENDL;} Adaptee::adaptee () {}adaptee::~adaptee () {}void adaptee::specificrequest () {std::cout<< "Adaptee:: Specificrequest "<<STD::ENDL;} Adapter::adapter () {}adapter::~adapter () {}void adapter::request () {this->specificrequest ();}

Main.cpp:

#include "Adapter.h" #include <iostream>using namespace Std;int main () {//adapter* ADT = new Adapter (); target* ADT = new Adapter (); Adt->request ();/*resultadaptee::specificrequest*/return 0;}

Demo Sample code 4: Object mode

Adapter.h:

#ifndef _adapter_h_#define _adapter_h_class target{public:target (); virtual ~target (); virtual void Request (); Protected:private:};class adaptee{public:adaptee (); ~adaptee (); void Specificrequest ();p Rotected:private:};class Adapter:public Target{public:adapter (adaptee* ade); ~adapter (); void Request ();p rotected:private:adaptee* _ade;}; #endif//~_adapter_h_

Adapter.cpp:

#include "Adapter.h" #include <iostream>target::target () {}target::~target () {}void target::request () {std:: cout<< "Target::request" <<STD::ENDL;} Adaptee::adaptee () {}adaptee::~adaptee () {}void adaptee::specificrequest () {std::cout<< "Adaptee:: Specificrequest "<<STD::ENDL;} Adapter::adapter (adaptee* ade) {this->_ade = ade;} Adapter::~adapter () {}void adapter::request () {_ade->specificrequest ();}

Main.cpp:

#include "Adapter.h" #include <iostream>using namespace Std;int main () {adaptee* ade = new Adaptee; target* ADT = new Adapter (ADE); Adt->request ();/*resultadaptee::specificrequest*/return 0;}

Adapter Mode structure diagram:


References:

1, "Big talk design mode C + +"

2, "design pattern refinement----GoF23 design mode Analysis"

3, "design mode----Reusable object Orientation Software Foundation"



Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Design mode mode Adapter (Adapter) excerpt

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.