Behavior.Strategy (behavioral mode - strategy mode)

Definition of Strategy Pattern

(1) Definition: Define a series of algorithms , encapsulate them one by one , and make them interchangeable . This pattern allows the algorithm to vary independently of the client using it.

  ①Algorithms are different implementations of the same interface with equal status and can be replaced with each other.

  ②Introducing the context object can realize the client that allows the algorithm to use it independently. Because this object is responsible for holding the algorithm , but not responsible for deciding which algorithm to choose, the function of choosing the algorithm is handed over to the client.

  ③ When the client notifies the context object to perform the function, the context will transfer the specific algorithm .

(2) The structure and description of the strategy pattern



  ①Strategy: Strategy interface, used to constrain a series of specific strategy algorithms. The Context uses this interface to invoke the algorithm defined by the concrete strategy implementation.

  ②ConcreteStrategy: The specific strategy implementation, that is, the specific algorithm implementation.

  ③Context: Context, responsible for interacting with specific policy classes. Usually holds a real strategy implementation , the context can also allow specific strategy classes to obtain context data , and even allow specific strategies to call back context methods

thinking strategy mode

(1) The essence of the strategy pattern : separate algorithms, choose implementation

(2) The focus of the strategy pattern is not how to implement the algorithm, but how to organize and call this series of algorithms , so as to make the program structure more flexible and have better maintainability and scalability.

(3) The equality of algorithms

  A great feature of the strategy mode is the equality of each strategy algorithm. For a series of specific strategy algorithms, everyone's status is exactly the same, so the algorithms can be replaced with each other . A policy algorithm can be described as follows: it is a different implementation of the same behavior. ( For example, it is the same behavior of discount, but merchants can choose different discount strategies at different times )

( 4) Who will choose the specific strategy algorithm

  ① One place is on the client side . When the context is used, the client side selects a specific strategy algorithm, and then sets the strategy algorithm to the context.

  ②There is another place where the specific strategy algorithm is selected by the context . The state mode can be implemented by specific states to switch between different states.

(5) Implementation of the Strategy role: Interfaces or abstract classes can be used, especially when multiple algorithms have common functions, Strategy can be implemented as abstract classes.

(6) The uniqueness of the runtime strategy: During the runtime, the strategy mode can only use one specific strategy implementation object at each moment. Although it can dynamically switch between different strategy implementations, only one can be used at the same time.

(7) Relationship between Context and Strategy

  ① In the strategy pattern, it is usually the context that implements the object using a specific strategy . Conversely, the policy implementation object can also obtain the required data from the context . Therefore, the context can be passed as a parameter to the strategy implementation object.

  ② In this case, the context encapsulates the data required by the specific strategy object to perform the algorithm operation, and the specific strategy object obtains the data by calling back the context.

Fault-tolerant recovery mechanism

(1) When the program is running, it should be done in a certain way under normal circumstances. At this time, if an error occurs, the system will not crash, but has the ability to tolerate errors .

(2) It can not only tolerate errors in program operation, but also provide a backup solution after errors, that is, a recovery mechanism to replace the function of normal execution, so that the program can continue to run downward. For example, log records are generally recorded in the database, but when the database is temporarily unavailable, they can be recorded in a text file first, and then transcribed into the database when appropriate.

[Programming Experiment] Logging Strategy

 


//behavioral mode - strategy mode
//Scenario: Fault Tolerance Recovery Mechanism (Strategy Mode + Template Method)
/*
    log to database and file
*/
#include <iostream>
#include <string>

using namespace std;

//Interface for logging policy
class CLogStrategy{
public:
	virtual void WriteLog(string log) = 0;//Record log
	virtual ~CLogStrategy(){}
};

/ / Implement the log strategy interface
// log to the database
class CDbLog : public CLogStrategy{
public:
	void WriteLog(string log){
		// Make an error, imitating a database disconnect
		try{if(log.length() >= 30)		throw -1;}
		catch(...){throw -1;}
		//When the data connection is normal, write directly to the database
		cout << "Write log : \"" << log << "\" into Database." << endl;
	}
};

//log log to file
class CFileLog : public CLogStrategy{
public:
	void WriteLog(string log){cout << "Write log : \"" << log << "\" into File." << endl;}
};

// context for logging
class CLogContext{
private:
	CLogStrategy* pStrategy;
public:
	CLogContext () {pStrategy = NULL;}
	~CLogContext(){Clr();}
	void Clr(){
		if(pStrategy != NULL){
			delete pStrategy; pStrategy = NULL;
		}
	}
	void DoLog(string log){
		 //In the context, implement the choice of specific strategies by yourself
		try{//Preference strategy: record to database
			Clr();
			pStrategy = new CDbLog();
			pStrategy->WriteLog(log);
		}
		catch(...){//If an error occurs, then record it in the file
			Clr();
			pStrategy = new CFileLog();
			pStrategy->WriteLog(log);
		}
		Clr();
	}
};

void StrategyTst()
{
	CLogContext oLogContext;
	oLogContext.DoLog("abcdefghijklmnopqrstuvwxyz");
	oLogContext.DoLog("abcdefghijklmnopqrstuvwxyz1234");
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324725660&siteId=291194637