Strategy Pattern of Behavioral Design Pattern [Design Pattern Series]

Series Article Directory

C++ skill series
Linux communication architecture series
C++ high-performance optimization programming series
Deep understanding of software architecture design series
Advanced C++ concurrent thread programming
design pattern series

Looking forward to your attention! ! !
insert image description here

现在的一切都是为将来的梦想编织翅膀,让梦想在现实中展翅高飞。
Now everything is for the future of dream weaving wings, let the dream fly in reality.

1. Introduction to strategy mode

⚠️ 意图:
Define a series of algorithms, encapsulate them one by one, and make them interchangeable.

⚠️ 主要解决:
In the case of multiple similar algorithms, using if...else is complicated and difficult to maintain.

⚠️ 何时使用:
A system has many, many classes, and what distinguishes them is their immediate behavior.

⚠️ 如何解决:
Encapsulate these algorithms into classes one by one, and replace them arbitrarily.

In Strategy Pattern the behavior of a class or its algorithm can be changed at runtime. This type of design pattern is a behavioral pattern.
The strategy pattern defines a series of algorithms or strategies, and encapsulates each algorithm in an independent class so that they can replace each other. By using the strategy pattern, different algorithms can be selected at runtime as needed without modifying the client code.
In the strategy pattern, we create objects representing various strategies and a context object whose behavior changes as the strategy object changes. A strategy object changes the execution algorithm of a context object.

insert image description here

Figure 1_1 Strategy pattern class diagram

Second, the advantages and disadvantages of the strategy model

2.1 Advantages

1. The algorithm can be switched freely. 2. Avoid using multiple conditional judgments. 3. Good scalability.

2.2 Disadvantages

1. There will be more strategies. 2. All policy classes need to be exposed to the outside world.

3. Strategy mode usage scenarios

1. If there are many classes in a system, and the difference between them is only their behavior, then using the strategy pattern can dynamically allow an object to choose a behavior among many behaviors. 2. A system needs to dynamically choose one of several algorithms. 3. If an object has many behaviors, if there is no appropriate mode, these behaviors have to be realized by using multiple conditional selection statements.

4. Realization of strategy mode

ReplaceAlgorithm is an abstract class that defines the interface of the algorithm. There are three classes inherited from this abstract class, that is, the specific algorithm implementation. The replacement algorithm needs to be used in the Cache class, so a ReplaceAlgorithm object is maintained.

Firstly, the definition of the replacement algorithm is given.

//抽象接口
class ReplaceAlgorithm
{
    
    
public:
	virtual void Replace() = 0;
};
//三种具体的替换算法
class LRU_ReplaceAlgorithm : public ReplaceAlgorithm
{
    
    
public:
	void Replace() {
    
     cout<<"Least Recently Used replace algorithm"<<endl; }
};
 
class FIFO_ReplaceAlgorithm : public ReplaceAlgorithm
{
    
    
public:
	void Replace() {
    
     cout<<"First in First out replace algorithm"<<endl; }
};
class Random_ReplaceAlgorithm: public ReplaceAlgorithm
{
    
    
public:
	void Replace() {
    
     cout<<"Random replace algorithm"<<endl; }
};

Then give the definition of Cache, which is very important here. The implementation of Cache directly affects the way customers use it. The key lies in how to specify the replacement algorithm.

Method 1: Directly specify through parameters and pass in a pointer to a specific algorithm.

//Cache需要用到替换算法
class Cache
{
    
    
private:
	ReplaceAlgorithm *m_ra;
public:
	Cache(ReplaceAlgorithm *ra) {
    
     m_ra = ra; }
	~Cache() {
    
     delete m_ra; }
	void Replace() {
    
     m_ra->Replace(); }
};

If this method is used, customers need to know the specific definitions of these algorithms. It can only be used in the following way, and you can see that too many details are exposed.

int main()
{
    
    
	Cache cache(new LRU_ReplaceAlgorithm()); //暴露了算法的定义
	cache.Replace();
	return 0;
}

Method 2: It is also specified directly through parameters, but instead of passing in a pointer, it is a label. In this way, customers only need to know the corresponding label of the algorithm, and do not need to know the specific definition of the algorithm.

//Cache需要用到替换算法
enum RA {
    
    LRU, FIFO, RANDOM}; //标签
class Cache
{
    
    
private:
	ReplaceAlgorithm *m_ra;
public:
	Cache(enum RA ra) 
	{
    
     
		if(ra == LRU)
			m_ra = new LRU_ReplaceAlgorithm();
		else if(ra == FIFO)
			m_ra = new FIFO_ReplaceAlgorithm();
		else if(ra == RANDOM)
			m_ra = new Random_ReplaceAlgorithm();
		else 
			m_ra = NULL;
	}
	~Cache() {
    
     delete m_ra; }
	void Replace() {
    
     m_ra->Replace(); }
};

Compared with method 1, this method is much more convenient to use. In fact, this method combines the simple factory pattern and the strategy pattern. The definition of the algorithm uses the strategy pattern, and the definition of the Cache actually uses the simple factory pattern.

int main()
{
    
    
	Cache cache(LRU); //指定标签即可
	cache.Replace();
	return 0;
}

In the above two methods, the constructor requires formal parameters. Can constructors take no parameters? The third implementation is given below.

Method 3: Use templates to implement. The algorithm is specified by the template's arguments. Of course, the parameters are still used, but not the parameters of the constructor. In the strategy mode, the passing of parameters is unavoidable, and the client must specify a certain algorithm.

//Cache需要用到替换算法
template <class RA>
class Cache
{
    
    
private:
	RA m_ra;
public:
	Cache() {
    
     }
	~Cache() {
    
     }
	void Replace() {
    
     m_ra.Replace(); }
};

The usage is as follows:

int main()
{
    
    
	Cache<Random_ReplaceAlgorithm> cache; //模板实参
	cache.Replace();
	return 0;
}

Supongo que te gusta

Origin blog.csdn.net/weixin_30197685/article/details/131927839
Recomendado
Clasificación