设计模式:策略模式(1)C++版

策略模式定义了算法族,将其封装起来,在其内部可相互替换。让它的变化独立于需要它的客户类。


其C++例子实现如下:

/*
* CONTENTS: DESIGN PATTERN, STRATEGY PATTERN
*   AUTHOR: YAO H. WANG
*     TIME: 2013-10-17 17:08:34
*  EDITION: 1
*
* ALL RIGHTS RESERVED!
*/

#include <iostream>

using namespace std;

/*
* 原则1:把变化的部分和不变的部分分开。
* 飞行行为和呱呱叫行为
*/

//飞行行为
class FlyBehavior
{
public:
	virtual void fly() = 0;
};

class FlyWithWings: public FlyBehavior
{
public:
	void fly()
	{
		cout << "I'm flying!!" << endl;
	}
};

class FlyNoWay: public FlyBehavior
{
public:
	void fly()
	{
		cout << "I can't fly" << endl;
	}
};

class FlyRocketPowered: public FlyBehavior
{
public:
	void fly()
	{
		cout <<  "I'm flying with a rocket!" << endl;
	}
};

//呱呱叫行为
class QuackBehavior
{
public:
	virtual void quack() = 0;
};

class Quack: public QuackBehavior
{
public:
	void quack()
	{
		cout << "Quack" << endl;
	}
};

class MuteQuack: public QuackBehavior
{
public:
	void quack()
	{
		cout << "<< Silence >>" << endl;
	}
};

class Squeak: public QuackBehavior
{
public:
	void quack()
	{
		cout << "Squeak" << endl;
	}
};

//客户类——鸭子
class Duck
{
public:
	/*
	* 原则2:多组合,少继承
	*/
	FlyBehavior *flyBehavior;
	QuackBehavior *quackBehavior;

private:
	virtual void display() = 0;

public:
	virtual void performFly()
	{
		flyBehavior->fly();
	}
	virtual void performQuack()
	{
		quackBehavior->quack();
	}
	virtual void setFlyBehavior(FlyBehavior *fb)
	{
		flyBehavior = fb;
	}
	virtual void setQuackBehavior(QuackBehavior *qb)
	{
		quackBehavior = qb;
	}

	virtual ~Duck()
	{
	}
};

class MallardDuck: public Duck
{
public:
	MallardDuck()
	{
		flyBehavior = new FlyWithWings();
		quackBehavior = new Quack();
	}

	void display()
	{
		cout << "I'm a real Mallard duck" << endl;
	}

	~MallardDuck()
	{
		delete flyBehavior;
		delete quackBehavior;
	}
};

class ModelDuck: public Duck
{
public:
	ModelDuck()
	{
		flyBehavior = new FlyNoWay();
		quackBehavior = new Quack();
	}

	void display()
	{
		cout << "I'm a model duck" << endl;
	}

	~ModelDuck()
	{
		delete flyBehavior;
		delete quackBehavior;
	}
};

//测试
void main()
{
	/*
	* 原则3: 针对接口编程,而不是针对实现编程
	*/
	Duck* mallard = new MallardDuck();
	mallard->performFly();
	mallard->performQuack();

	Duck* model = new ModelDuck();
	model->performFly();
	model->setFlyBehavior(new FlyRocketPowered());
	model->performFly();

	delete mallard;
	delete model;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值