Strategy设计模式举例。
看图:
代码实现:
#include <iostream>using namespace std;class FlyBehavior {
public:virtual void fly() = 0;
};class QuackBehavior {
public:virtual void quack() = 0;
};class FlyWithWings :public FlyBehavior {
public:void fly() { cout << "fly with wings!" << endl; }
};class FlyNoWay :public FlyBehavior {
public:void fly() { cout << "can not fly!" << endl; }
};class Quack :public QuackBehavior {
public:void quack() { cout << "gaga!" << endl; }
};class Squeak :public QuackBehavior {
public:void quack() { cout << "fricktion !" << endl; }
};class QuackNoWay :public QuackBehavior {
public :void quack() { cout << "can not sound!" << endl; }
};class Duck {
protected:FlyBehavior *flyBehavior;QuackBehavior *quackBehavior;
public:void fly() { flyBehavior->fly(); }void quack() { quackBehavior->quack(); }virtual void display() = 0;};class RubberDuck :public Duck {
public:RubberDuck() {flyBehavior = new FlyNoWay;quackBehavior = new Squeak;}void display() { cout <<"rubber duck" << endl; };
};
细节:
- 在Duck类中,new的是虚类(virtual)或者虚方法类,而在RubberDuck中new的是实类。接下来,调用实类的方法时,会根据不同的实类调用不同的实方法。
- new FlyNoWay 也可以写成new FlyNoWay(),但是最好写成new FlyNoWay()。
- 结合本例,图中的聚合/集合该如何理解?