C++设计模式-策略模式(Strategy)基本轮廓

策略模式(Strategy):它定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。

context,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用。

策略模式和工厂模式的不同之处:
工厂来生成算法对象,这没有错,但算法只是一种策略,最重要的是这些算法是随时间都可能互相替换的,这就是变化点,而封装变化就是面向对象的一个重要的思维方式,
策略模式结构图如下所示:

 

来举一个栗子:

程序运行截图如下;

C++设计模式-策略模式(Strategy)基本轮廓_第1张图片

源码如下:

strategy.h

#pragma once

#include 
using namespace std;

class Strategy{

public:
	virtual void algorithmInterface() = 0;
	virtual ~Strategy(){
		cout << "~Strategy() called!" << endl;
	}

};

class ConcreteStrategyA: public Strategy{

public:
	void algorithmInterface(){

		cout << "arithmetic A is called!" << endl;
	}

	~ConcreteStrategyA(){

		cout << "~ConcreteStrategyA() called!" << endl;
	}
};

class ConcreteStrategyB: public Strategy{

public:
	void algorithmInterface(){

		cout << "arithmetic A is called!" << endl;
	}

	~ConcreteStrategyB(){
	
		cout << "~ConcreteStrategyB() called!" << endl;
	}
};

class ConcreteStrategyC: public Strategy{

public:
	void algorithmInterface(){

		cout << "arithmetic C is called!" << endl;
	}

	~ConcreteStrategyC(){

		cout << "~ConcreteStrategyC() called!" << endl;
	}
};

class Context{
	
public:
	Context(Strategy *strategy){
		m_strategy = strategy;
	}

	~Context(){
		delete m_strategy;
	}

	void contextInterface(){
		m_strategy->algorithmInterface();
	}


private:
	Strategy *m_strategy;
};

main.cpp

#include "strategy.h"

int main(){

	Context *contextA, *contextB, *contextC;
	//由于实例化不同的策略,所以最终在调用context->contextInterface()时,所获得的结果就不尽相同
	contextA = new Context(new ConcreteStrategyA);
	contextA->contextInterface();
	delete contextA;

	cout << endl << "----------**********----------" << endl;
	
	contextB = new Context(new ConcreteStrategyB);
	contextB->contextInterface();
	delete contextB;

	cout << endl << "----------**********----------" << endl;

	contextC = new Context(new ConcreteStrategyC);
	contextC->contextInterface();
	delete contextC;

	getchar();
	return 0;
}

 

你可能感兴趣的:(C/C++,设计模式,C,设计模式,策略模式)