Headfirst设计模式的C++实现——策略模式(Strategy)

前言

最近在学习《Headfirst设计模式》,里面的例子都是Java的。但是我对Java并不熟悉,所以试着用C++来实现书中的例子。

先来看看Duck以及子类

Duck.h

 #include <iostream>
#include "FlyBehavior.h" class Duck
{
private:
FlyBehavior *m_p_fly_behavior;
public:
virtual void quack() { std::cout << "--quack--" << std::endl; }
virtual void swim() { std::cout << "--swim--" << std::endl; }
virtual void display() { std::cout << "--duck--" << std::endl; } virtual void fly() { if ( m_p_fly_behavior) { m_p_fly_behavior->fly(); } };
void set_fly_behavior( FlyBehavior *p_fly_behavior) { m_p_fly_behavior = p_fly_behavior; } Duck() : m_p_fly_behavior(NULL) {}
virtual ~Duck() { if (m_p_fly_behavior) { delete m_p_fly_behavior; } }
};

MallardDuck.h

 #include "Duck.h"
#include "FlyWithWings.h" class MallardDuck : public Duck
{
public:
void display() { std::cout << "--MallardDuck--" << std::endl; }
MallardDuck() { set_fly_behavior( new FlyWithWings() ); }
};

RedheadDuck.h

 #include "FlyWithWings.h"
class RedheadDuck : public Duck
{
public:
void display() { std::cout << "--RedheadDuck--" << std::endl; }
RedheadDuck() { set_fly_behavior( new FlyWithWings() ); }
};

RubberDuck.h

 #include "FlyNoWay.h"

 class RubberDuck : public Duck
{
public:
void display() { std::cout << "--RubberDuck--" << std::endl; }
void quack() { std::cout << "--squeak--" << std::endl; }
RubberDuck() { set_fly_behavior( new FlyNoWay() ); }
};

再来看看FlyBehavior类及其子类

FlyBehavior.h

 #include <iostream>

 class FlyBehavior
{
public:
virtual void fly() {};
virtual ~FlyBehavior() {};
};

FlyWithWings.h

 #include "FlyBehavior.h"

 class FlyWithWings : public FlyBehavior
{
public:
void fly () { std::cout << "--fly with wings--" << std::endl; }
};

FlyNoWay.h

 #include "FlyBehavior.h"

 class FlyNoWay : public FlyBehavior
{
public:
void fly() { std::cout << "--can not fly--" << std::endl; }
};

最后是主函数

main.cpp

 #include "MallardDuck.h"
#include "RedheadDuck.h"
#include "RubberDuck.h"
#include <vector> void test()
{
std::vector<Duck *> p_ducks;
p_ducks.push_back( new MallardDuck() );
p_ducks.push_back( new RedheadDuck() );
p_ducks.push_back( new RubberDuck() ); for (std::vector<Duck *>::iterator it = p_ducks.begin(); it < p_ducks.end(); it ++)
{
std::cout << std::endl;
(*it)->display();
(*it)->quack();
(*it)->swim();
(*it)->fly();
delete (*it);
}
} int main()
{
while (true)
{
test();
}
}

稍作解释

main函数中死循环的调用test函数的意图是测试以上实现有没有内存泄露。

上一篇:swift 2.2 语法 (上)


下一篇:ASP获取json天气信息