C++ 开闭模式代码实例

开闭模式是尽量不改动源代码,使用多态的方式扩展源代码

#include<iostream>
using namespace std;

// 写一个抽象类
class AbstractCaculator
{
public:
	virtual int getResult() = 0;
	virtual void setOperatorNumber(int a, int b) = 0;

};

class PlusCaculator:public AbstractCaculator
{
public:
	void setOperatorNumber(int a, int b)
	{
		mA = a;
		mB = b;
	}
	virtual int getResult()
	{
		return mA + mB;
	}

private:
	int mA;
	int mB;
};

class MinuteCaculator :public AbstractCaculator
{
public:
	void setOperatorNumber(int a, int b)
	{
		mA = a;
		mB = b;
	}
	virtual int getResult()
	{
		return mA - mB;
	}

private:
	int mA;
	int mB;
};

class MultiplyCaculator :public AbstractCaculator
{
public:
	void setOperatorNumber(int a, int b)
	{
		mA = a;
		mB = b;
	}
	virtual int getResult()
	{
		return mA * mB;
	}

private:
	int mA;
	int mB;
};

void test01()
{
	AbstractCaculator* caculator = new PlusCaculator;     // 基类指针
	caculator->setOperatorNumber(10,20);
	cout << "ret:" << caculator->getResult() << endl;


}

int main()
{
	test01();
	system("pause");
}

 

点赞