I understand the design pattern (C ++ implementation) -- strategy Pattern)

Source: Internet
Author: User
Overview:

Everyone needs to "pay personal income tax", but "pay personal income tax in the United States" and "pay personal income tax in China" have different tax calculation methods. The policy mode is to package the algorithm, which separates the responsibility for using the algorithm from the algorithm itself and delegates it to different object management. Rule mode typically packs a series of algorithms into a series of policy classes and serves as a subclass of an abstract policy class. In one sentence, it is: "prepare a group of algorithms and encapsulate each algorithm to make them interchangeable ".

Class Diagram and instance:

Context ):

1. The concretestrategy algorithm is required.

2. Maintain a strategy instance internally.

3. dynamically sets the specific implementation algorithm of strategy during runtime.

4. Interaction and data transmission with strategy.

Strategy (abstract policy class): defines a public interface. Different algorithms implement this interface in different ways. context uses this interface to call different algorithms, which are generally implemented using interfaces or abstract classes.

Concretestrategy: implements the interfaces defined by Strategy and provides specific algorithm implementations.

Here, we use the characters in CS as an example. Each person can have several weapons, dynamically switch between weapons, and have a unified attack command:

#include <iostream>using namespace std;class WeaponBehavior{public:void virtual useWeapon() = 0;};class AK47:public WeaponBehavior{public:void useWeapon(){cout << "Use AK47 to shoot!" << endl;}};class Knife:public WeaponBehavior{public:void useWeapon(){cout << "Use Knife to kill!" << endl;}};class Character{public:Character(){weapon = 0;}void setWeapon(WeaponBehavior *w){this->weapon = w;}void virtual fight() = 0;protected:WeaponBehavior *weapon;};class King:public Character{public:void fight(){cout << "The king:" ;if ( this->weapon == NULL){cout << "You don't have a weapon! Please Set Weapon!" << endl;}else{ weapon->useWeapon();}}};int main(){    WeaponBehavior *ak47 = new AK47();WeaponBehavior *knife = new Knife();     Character *kin = new King();      kin->fight();   cout << endl; kin->setWeapon(ak47);kin->fight();cout << endl;kin->setWeapon(knife);kin->fight();return 0;}

Applicability:

1. Multiple classes only differ in performance behavior. You can use the Strategy Mode to dynamically select the behavior to be executed during running.

2. Different policies (algorithms) must be used in different situations, or they may be implemented in other ways in the future.

3. The implementation details of specific policies (algorithms) are hidden from customers, and they are completely independent of each other.

Advantages and disadvantages:

Advantages:

1. The policy mode provides methods for managing related algorithm families. The hierarchical structure of a policy class defines an algorithm or behavior family. Proper use of inheritance allows you to move public code to the parent class to avoid code duplication.

2. The policy mode can avoid the use of multi-condition (if-else) statements. Multi-condition statements are not easy to maintain. they mix the logic of which algorithm or behavior is adopted with the logic of the algorithm or behavior and are all listed in a multi-Condition Statement, it is more primitive and backward than the inheritance method.

Disadvantages:

1. The client must know all the policy classes and decide which one to use. This means that the client must understand the differences between these algorithms so that appropriate algorithm classes can be selected in a timely manner. In other words, the policy mode is only applicable when the client knows the algorithm or behavior.

2. Because the policy mode encapsulates each specific policy implementation into a class separately, if there are many alternative policies, the number of objects will be considerable.

Differences from other design patterns:

1. With the status Mode

In solving the problem, the state mode solves the change of the internal state, while the policy mode solves the change of the internal algorithm. In the solution, the state mode changes the state of self-control, and the policy mode is used by external entities to determine what policies are used.

2. Simple factory Model

The simple factory mode is the creation mode, which focuses on Object creation. Rule mode is a behavior mode that focuses on behavior encapsulation. The simple factory mode returns a suitable class for you based on different conditions, and then the caller uses the class returned by the factory class to complete the corresponding operation. In policy mode, you must first create a class instance that you want to use, and then pass the instance as a parameter, and then use the instance to call unused algorithms. In the simple factory mode, an object is instantiated by selecting a class based on conditions. In the policy mode, the work of the selected object is handed over to the user of the mode, which does not select the object itself.


Lcl_data was originally created in csdn. Net [http://blog.csdn.net/lcl_data/article/details/10255125]

For more design patterns, see the design patterns I understand.

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.