c++ 策略模式

#pragma once
class IStrategy_Test
{
     
public:
	virtual int calculate(int a, int b) = 0;
};

class Calculate_Add : public IStrategy_Test
{
     
	int calculate(int a, int b) override 
	{
     
		return a + b;
	}
};

class Calculate_Subtract : public IStrategy_Test
{
     
	inline int calculate(int a, int b) override {
      return a - b; }
};

class Calculate
{
     
public:
	enum CALCULATE_TYPE
	{
     
		CALCULATE_TYPE_ADD = 0,
		CALCULATE_TYPE_SUBTRACT,
	};
	void set_calculate_type(CALCULATE_TYPE type)
	{
     
		switch (type)
		{
     
		case Calculate::CALCULATE_TYPE_ADD:
			interface_calculate_ = new Calculate_Add();
			break;
		case Calculate::CALCULATE_TYPE_SUBTRACT:
			interface_calculate_ = new Calculate_Subtract();
			break;
		default:
			break;
		}
	}
	int calculate(int a, int b)
	{
     
		return interface_calculate_->calculate(a, b);
	};


private:
	IStrategy_Test* interface_calculate_;
};

使用:
#include

#include"Strategy_Test.h"

int main()
{
     
	Calculate computer;
	computer.set_calculate_type(Calculate::CALCULATE_TYPE_SUBTRACT);
	printf("hello %d\n",computer.calculate(2,1));
}

你可能感兴趣的:(設計模式,c++)