Strategy mode details-design mode (13)

Source: Internet
Author: User

Strategy mode Source:

in software development also often encounter similar situation, to achieve a certain function has a number of algorithms or strategies, we can choose different algorithms or strategies according to the environment or conditions to complete the function. such as finding, sorting, and so on, a commonly used method is hard-coded (Coding) in a class, if you need to provide a variety of search algorithms, you can write these algorithms into a class, in the class to provide multiple methods, each method corresponding to a specific search algorithm ; Of course, these lookup algorithms can be encapsulated in a unified approach, through the if...else ... or case and other conditional judgment statements to make the selection. Both of these implementations can be called hard-coded, and if a new lookup algorithm needs to be added, the source code of the encapsulated algorithm class needs to be modified, and the client calling code needs to be changed. In this algorithm class to encapsulate a large number of search algorithms, the class code will be more complex, maintenance is more difficult. This is even more undesirable if we include these policies on the client, which will cause the client program to be large and difficult to maintain, and the problem will become more serious if there are a large number of algorithms to choose from.

Strategy Mode effect:

The problem to be solved by the strategy mode and template mode is the same (similar), in order to decouple the specific implementation of the business logic (algorithm) and the abstraction interface. The strategy mode encapsulates the logic (algorithm) into a class (Context) and implements the implementation of the specific algorithm in a combined way, and then delegates the implementation of the abstract interface to the composite object.

The strategy mode UML structure is shown in Figure 1:


The composition of the Strategy pattern:

Environment Class (Context): Configured with a Concretestrategy object. Maintains a reference to the Strategy object. You can define an interface to let strategy access its data.
Abstract Policy Classes (strategy): defines the public interface for all supported algorithms. The context uses this interface to invoke an algorithm defined by a concretestrategy.
Specific policy Classes (Concretestrategy): Implement a specific algorithm with strategy interface.

code example for strategy mode:

Strategy.h

#ifndef _strategy_h_#define _strategy_h_class strategy{public:    ~strategy ();    virtual void Algrithminterface () =0;protected:    strategy ();p Rivate:};class concretestrategya:public Strategy{ Public:    Concretestrategya ();    ~concretestrategya ();    virtual void Algrithminterface ();p rotected:private:};class concretestrategyb:public strategy{public:    Concretestrategyb ();    ~concretestrategyb ();    virtual void Algrithminterface ();p rotected:private:};/* This class is the key to strategy mode  and the fundamental difference between the strategy pattern and the template pattern.  *strategy implementation of the algorithm through "combination" (implementation) of the heterogeneous,  and the template mode is inherited, the difference between the two patterns is to  inherit and combine the two ways to implement interface reuse */class Context{public:    Context (strategy*);    ~context ();    void DoAction ();p rivate:    strategy* _strategy;}; #endif

Strategy.cpp

#include "Strategy.h" #include "iostream" using namespace std; Strategy::strategy () {}strategy::~strategy () {}concretestrategya::concretestrategya () {}ConcreteStrategyA::~ Concretestrategya () {}void concretestrategya::algrithminterface () {    cout << "Concretestrategya:: Algrithminterface "<< Endl;} Concretestrategyb::concretestrategyb () {}concretestrategyb::~concretestrategyb () {}void ConcreteStrategyB:: Algrithminterface () {    cout << "Concretestrategyb::algrithminterface" << Endl;} Context::context (strategy* strategy) {    this->_strategy = strategy;} Context::~context () {    delete this->_strategy;} void Context::D oaction () {    this->_strategy->algrithminterface ();}

Main.cpp


#include "Strategy.h" int main () {/    *    strategy mode and template mode are actually two ways to implement an abstract interface: the difference between inheritance and composition.    to implement an abstract interface, inheritance is a way: we declare an abstract interface in a base class and place specific implementations in a specific subclass. A    combination (delegate) is another way: we place the implementation of the interface in the combined object, placing the abstract interface in the composition class. Both    of these approaches have advantages and disadvantages    *///    strategy A and B replaceable    strategy* pStr = new Concretestrategya ();    context* Pcon = new Context (PSTR);    Pcon->doaction ();    PSTR = new Concretestrategyb ();    Pcon = new Context (PSTR);    Pcon->doaction ();    return 0;}

Strategy Mode Usage Scenarios:

(1). Many of the related classes are simply behavior-specific. Policy provides a way to configure a class with one behavior in multiple behaviors. That is, a system needs to dynamically select one of several algorithms.

(2). You need to use different variants of an algorithm. For example, you might define algorithms that reflect different spatial/temporal tradeoffs. When these variants are implemented as a class hierarchy of an algorithm, the policy mode can be used.

(3). The algorithm uses data that the customer should not know about. You can use the policy mode to avoid exposing complex, algorithmic-related data structures.

(4). A class defines a variety of behaviors, and these behaviors appear as multiple conditional statements in the operation of this class. The related conditional branches are moved into their respective strategy classes in place of these conditional statements.

Strategy Patterns and Template comparative analysis of Pattern pros and Cons:

You can see that the strategy mode and the template pattern solve similar problems, and as analyzed in template mode, 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: we declare an abstract interface in a base class and place specific implementations in a specific subclass. A combination (delegate) is another way: we place the implementation of the interface in the combined object, placing the abstract interface in the composition class. Each of these two approaches has advantages and disadvantages, which are listed first:

1. Inheritance:

Advantages:

(1). Easy to modify and extend the implementations that are reused.

Disadvantages:

(1). The encapsulation is destroyed, and the implementation details of the parent class in the inheritance are exposed to subclasses;

(2). "White box" multiplexing for reasons in (1);

(3). When the implementation of the parent class changes, all its subclasses will have to change

(4). Implementations inherited from the parent class cannot be changed during runtime (determined during compilation).

2. Combination:

Advantages:

(1). "Black box" multiplexing, because the inner details of the contained object are not visible externally;

(2). Good encapsulation, the reason is (1);

(3). The dependency of the implementation and abstraction is small (the dependency between the combined object and the composed object is small);

(4). The implementation can be dynamically defined during runtime (through a pointer to the same type, typically a pointer to an abstract base class).

Disadvantages:

(1). There are too many objects in the system.

Strategy Pattern Usage Summary:

From the above comparison, we can see that the combination can achieve better results than inheritance, so in object-oriented design there is a very important principle is: priority to use (object) combination, rather than (Class) inheritance (Favorcomposition overinheritance).

In fact, inheritance is a compelling way to make the coupling between a base class and a specific subclass strong. For example, the class of primitive operations defined in ConcreteClass1 in template mode is not directly reusable (unless you inherit from AbstractClass, see Template Schema documentation for specific analysis). The method of combination (delegation) has very little coupling, the dependence between implementation (Implementation) and interface (abstract interface) is very small, for example, in this implementation, the implementation of Concretestrategya is easy to be reused by other classes, For example, if we want to define another context class Anothercontext, it is easy to reuse the implementation of Concretestrategya by combining a pointer to strategy.

The difference between inheritance and composition is illustrated in the bridge mode problem and bridge mode analysis. See corresponding mode resolution.

In addition, the strategy mode has similarities with the state pattern, but the states ' mode focuses on the different operations of the objects under different conditions. The difference between the two is that there is a reference to the context in the specific implementation class in state mode, while the strategy mode does not.

In addition, strategy mode is a relatively easy to understand and use the design pattern, the strategy pattern is the encapsulation of the algorithm, it divides the algorithm's responsibility and the algorithm itself, delegated to different object management. The strategy pattern typically encapsulates a series of algorithms into a set of policy classes as subclasses of an abstract policy class. In a word, it is "preparing a set of algorithms and encapsulating each algorithm so that they can be interchanged". In strategy mode , it is up to the client to decide under what circumstances the specific policy role should be used.

Strategy mode only encapsulates the algorithm, provides a new algorithm to insert into the existing system, and the old algorithm from the system "retirement" convenience, the strategy mode does not decide when to use which algorithm, the choice of the algorithm is determined by the client. This improves the flexibility of the system to a certain extent, but the client needs to understand the differences between all the specific policy classes in order to choose the appropriate algorithm, which is one of the drawbacks of the strategy model, which in some way increases the difficulty of using the client.


Strategy mode details-design mode (13)

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.