Excerpt from the policy mode design pattern (strategy)

Source: Internet
Author: User

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

Creates an instance of the schema abstraction. A system is independent of the objects that create, group, and represent it. A class-creation pattern uses inheritance to change the class that is instantiated, and an object-creation pattern entrusts the instantiation to another object. The creation pattern has two recurring themes. First. They all 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. Therefore, the creation pattern is created in what. Who created it. How it was created. And when to create these aspects gives very great flexibility. They agreed to configure a system with "product" objects with very different structures and functions. 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. It is a description of how to combine some objects. Some ways to implement new functionality. The ability to change the combination of objects at execution time. So 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.

The behavior pattern not only describes the patterns of objects or classes, but 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 (Abstraction Factory mode). 3, Singleton (single case mode). 4, builder (builder mode, generator mode), 5, Prototype (prototype mode).

The structure mode contains : 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. Let the subclass 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 a class has only one instance and provides a global access point to it.

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, and the facade schema 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. Some of the steps are deferred to 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 by eliminating the need for explicit reference to each other. And be able to independently change the interactions between them.

Command: Encapsulates a request as an object, allowing you to use different requests to account for the customer. 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: a coupling between the sender and receiver of the cancellation request, allowing 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.

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, a representation of the grammar that defines it. and defines an interpreter that uses that representation to interpret sentences in the language.

Strategy: (1), intent: Define a series of algorithms, encapsulate them one by one, and make them interchangeable with each other. This mode allows the algorithm to be independent of the customers who use it.

(2), applicability: A, a lot of related classes are only the behavior of different. Policy provides a way to configure a class with one behavior in multiple behaviors.

B, you need to use a different variant of the algorithm.

C, the algorithm uses data that the customer should not know.

You can use the policy mode to avoid exposing complex, algorithmic-related data structures. D, a class defines a variety of behaviors, and these behaviors occur in the operations of this class in the form of multiple conditional statements.

The related conditional branches are moved into their respective strategy classes in place of these conditional statements.

(3), advantages and disadvantages: A, correlation Algorithm series: Strategy class hierarchy defines a series of reusable algorithms or behaviors for the context.

Inheritance helps to extract public functionality from these algorithms.

B, an alternative to inheritance: inheritance provides a way to support multiple algorithms or behaviors.

You can generate a subclass of a context class directly. thereby gives it with different behavior.

However, this will make the behavior hard line into the context, and the implementation of the algorithm and the implementation of the context mixed up, so that the context is difficult to understand, difficult to maintain and difficult to expand. And it is not possible to dynamically change the algorithm. Finally you get a bunch of related classes, the only difference between them is the algorithm or behavior they use. Encapsulating the algorithm in a separate strategy class allows you to change it independently of its context, making it easy to switch, easy to understand, and easy to extend. C. Some conditional statements are eliminated: The strategy mode provides an alternative to selecting the desired behavior with a conditional statement. When different behaviors are stacked in a class. It is very difficult to avoid using conditional statements to select the appropriate behavior. These conditional statements are eliminated by encapsulating the behavior in a separate strategy class. D. Choice of implementation: The strategy model provides different implementations of the same behavior. Customers can choose from different strategies based on different time/space tradeoff requirements.

E, customers must understand the different strategy: this model has a potential disadvantage, is that a customer to choose a suitable strategy must know how these strategy are different. You may have to expose your customers to detailed implementation issues at this point. It is therefore only necessary to use the strategy model when these different behavioral variants are related to the customer's behavior.

Communication overhead between F, strategy, and context: whether the algorithm implemented by each concretestrategy is simple or complex. They all share the interface defined by the strategy. It is therefore very likely that some concretestrategy will not use all the information passed to them through this interface; The simple concretestrategy may not be using whatever information is in it. This means that sometimes the context creates and initializes a number of parameters that will never be used. Assuming that there is such a problem, there is a need for tighter coupling between the strategy and the context.

H, number of objects added: Strategy added the number of objects in an app. Sometimes you can reduce this overhead by implementing strategy as a stateless object that can be shared by each context. Whatever the rest of the state is maintained by the context. The context passes this state over every request to the Strategy object. Shared strategy should not maintain state between invocations.

(4), strategy: Define the algorithm family. Individually packaged together. So that they can replace each other, let the algorithm change. Does not affect the user. The members of the suitable class are mainly method-based, the algorithm often changes, and the unit test is simplified (since each algorithm has its own class.) Can be tested separately via its own interface). The strategy model and the simple factory are basically the same, but the simple factory model can only solve the object creation problem, and the policy pattern should be used for the frequently changing algorithm.

(5), strategy mode and template mode to solve the problem is the same (similar), is to give the business logic (algorithm) detailed implementation and decoupling between the abstract interface. The strategy pattern encapsulates the logic (algorithm) into a class (Context). By combining the actual composition of the detailed algorithm into the object, and then entrust the implementation of the abstract interface to the realization of the composite object. The state mode also has similar functionality.

The strategy pattern and the template pattern are actually two ways to implement an abstract interface: the difference between inheritance and composition. To implement an abstract interface. Inheritance is a way of declaring an abstract interface in a base class, placing a detailed implementation in a detailed subclass. Combination (entrusted) is the second way: we put the implementation of the interface in the combined object, the abstract interface in the composition class. Both of these approaches have advantages and disadvantages: A, Inheritance: Strengths: Easy to change and extend the implementations that are reused.

Disadvantage: It destroys encapsulation, the implementation details of the parent class in the inheritance are exposed to subclasses; "White box" multiplexing. When the implementation of the parent class changes, all its subclasses will have to be changed, and the actual execution period that is inherited from the parent class cannot be changed (it has been determined during compilation). B, Combination: Advantages: "Black box" reuse. Because the inner details of the contained object are not visible externally; the dependencies of the implementation and abstraction are very small (the dependency between the combined object and the composed object is small); the ability to dynamically define the implementation during execution (through a pointer to the same type, typically an abstract base class pointer).

Disadvantage: There are too many objects in the system.

(6), strategy mode and state mode also have similarities. However, the state pattern focuses on objects that operate differently in different states.

The difference between the two is that a reference to the context in the class is implemented in the State schema in detail. And the strategy mode is not.

Demo Sample Code 1:

#include <iostream>using namespace std;//strategy base classes Class Coperation{public:int M_nfirst;int m_nsecond;virtual double GetResult () {Double dresult = 0;return dresult;}};/ /Policy Detail Class----addition class Addoperation:public coperation{public:addoperation (int a, int b) {M_nfirst = A;m_nsecond = b;} Virtual Double GetResult () {return m_nfirst + M_nsecond;}}; Class context{private:coperation* Op;public:context (coperation* temp) {op = temp;} Double GetResult () {return op->getresult ();}};/ /clientint Main () {int A, B;char c;cin>>a>>b;cout<< "Please enter operator:"; Cin>>c;switch (c) {case ' + ': { context* context = new context (new Addoperation (A, b)); Cout<<context->getresult () <<endl;break; }default:break;} /*result58 Please enter operator: +13*/return 0;}

Demo Sample Code 2:

Strategy and Factory Integration: the client simply needs to access the context class. Without knowing any other information, the low-coupling is achieved. #include <iostream>using namespace std;//strategy base classes Class Coperation{public:int M_nfirst;int m_nsecond;virtual double GetResult () {Double dresult = 0;return dresult;}};/ /Policy Detail Class----addition class Addoperation:public coperation{public:addoperation (int a, int b) {M_nfirst = A;m_nsecond = b;} Virtual Double GetResult () {return m_nfirst + M_nsecond;}}; Class context{private:coperation* Op;public:context (char cType) {switch (cType) {case ' + ': op = new Addoperation (5, 8); Break;default:break;}} Double GetResult () {return op->getresult ();}};/ /clientint Main () {int A, b;cin>>a>>b; context* test = new Context (' + '); Cout<<test->getresult () <<endl;/*result2513*/return 0;}

Demo Sample Code 3:

Strategy.h:

#ifndef _strategy_h_#define _strategy_h_class strategy{public:strategy (); virtual ~strategy (); virtual void Algrithminterface () = 0;protected:private:};class concretestrategya:public Strategy{public:concretestrategya (); Virtual ~concretestrategya (); void Algrithminterface ();p rotected:private:};class concretestrategyb:public Strategy{ Public:concretestrategyb (); virtual ~concretestrategyb (); void Algrithminterface ();p rotected:private:}; #endif//~_ Strategy_h_

Strategy.cpp:

#include "Strategy.h" #include <iostream>using namespace std; Strategy::strategy () {}strategy::~strategy () {cout<< "~strategy ..." <<ENDL;} void Strategy::algrithminterface () {}concretestrategya::concretestrategya () {}concretestrategya::~ Concretestrategya () {cout<< "~concretestrategy ..." <<ENDL; void Concretestrategya::algrithminterface () {cout<< "Test Concretestrategya ..." <<ENDL; Concretestrategyb::concretestrategyb () {}concretestrategyb::~concretestrategyb () {cout<< "~ Concretestrategyb ... "<<ENDL; void Concretestrategyb::algrithminterface () {cout<< "Test concretestrategyb ..." <<ENDL;

Context.h:

#ifndef _context_h_#define _context_h_class strategy;/* This class is the key to the strategy pattern, which is also the fundamental difference between the strategy pattern and the template pattern. Strategy realizes the heterogeneity of the algorithm by "combining" (entrusting), while the template mode takes the way of inheritance. The difference between these two patterns is also the difference between inheriting and combining two ways of implementing interface Reuse */class Context{public:context (strategy* STG); ~context (); void DoAction ();p rotected: Private:strategy* _stg;}; #endif//~_context_h_

Context.cpp:

#include "Context.h" #include "Strategy.h" #include <iostream>using namespace std; Context::context (strategy* stg) {_STG = STG;} Context::~context () {if (!_STG) delete _stg;} void Context::D oaction () {_stg->algrithminterface ();}

Main.cpp:

#include "Context.h" #include "Strategy.h" #include <iostream>using namespace Std;int main () {strategy* PS = new Concretestrategya (); context* pc = new Context (PS);p c->doaction (); if (NULL! = PC) Delete pc;/*resulttest Concretestrategya ... */return 0;}

Policy Mode structure diagram:


References:

1, "Big talk design mode C + +"

2, "design pattern refinement----GOF23 Type design Analysis Mode"

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

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

Excerpt from the policy mode design pattern (strategy)

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.