策略模式:定义了算法族,将其封装起来,在其内部可相互替换。让它的变化独立于需要它的客户类。
其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;
}