标签:
前言
最近在学习《Headfirst设计模式》,里面的例子都是Java的。但是我对Java并不熟悉,所以试着用C++来实现书中的例子。
先来看看Duck以及子类
Duck.h
1 #include <iostream> 2 #include "FlyBehavior.h" 3 4 class Duck 5 { 6 private: 7 FlyBehavior *m_p_fly_behavior; 8 public: 9 virtual void quack() { std::cout << "--quack--" << std::endl; } 10 virtual void swim() { std::cout << "--swim--" << std::endl; } 11 virtual void display() { std::cout << "--duck--" << std::endl; } 12 13 virtual void fly() { if ( NULL != m_p_fly_behavior) { m_p_fly_behavior->fly(); } }; 14 void set_fly_behavior( FlyBehavior *p_fly_behavior) { m_p_fly_behavior = p_fly_behavior; } 15 16 Duck() : m_p_fly_behavior(NULL) {} 17 virtual ~Duck() { if (m_p_fly_behavior) { delete m_p_fly_behavior; } } 18 };
MallardDuck.h
1 #include "Duck.h" 2 #include "FlyWithWings.h" 3 4 class MallardDuck : public Duck 5 { 6 public: 7 void display() { std::cout << "--MallardDuck--" << std::endl; } 8 MallardDuck() { set_fly_behavior( new FlyWithWings() ); } 9 };
RedheadDuck.h
1 #include "FlyWithWings.h" 2 class RedheadDuck : public Duck 3 { 4 public: 5 void display() { std::cout << "--RedheadDuck--" << std::endl; } 6 RedheadDuck() { set_fly_behavior( new FlyWithWings() ); } 7 };
RubberDuck.h
1 #include "FlyNoWay.h" 2 3 class RubberDuck : public Duck 4 { 5 public: 6 void display() { std::cout << "--RubberDuck--" << std::endl; } 7 void quack() { std::cout << "--squeak--" << std::endl; } 8 RubberDuck() { set_fly_behavior( new FlyNoWay() ); } 9 };
再来看看FlyBehavior类及其子类
FlyBehavior.h
1 #include <iostream> 2 3 class FlyBehavior 4 { 5 public: 6 virtual void fly() {}; 7 virtual ~FlyBehavior() {}; 8 };
FlyWithWings.h
1 #include "FlyBehavior.h" 2 3 class FlyWithWings : public FlyBehavior 4 { 5 public: 6 void fly () { std::cout << "--fly with wings--" << std::endl; } 7 };
FlyNoWay.h
1 #include "FlyBehavior.h" 2 3 class FlyNoWay : public FlyBehavior 4 { 5 public: 6 void fly() { std::cout << "--can not fly--" << std::endl; } 7 };
最后是主函数
main.cpp
1 #include "MallardDuck.h" 2 #include "RedheadDuck.h" 3 #include "RubberDuck.h" 4 #include <vector> 5 6 void test() 7 { 8 std::vector<Duck *> p_ducks; 9 p_ducks.push_back( new MallardDuck() ); 10 p_ducks.push_back( new RedheadDuck() ); 11 p_ducks.push_back( new RubberDuck() ); 12 13 for (std::vector<Duck *>::iterator it = p_ducks.begin(); it < p_ducks.end(); it ++) 14 { 15 std::cout << std::endl; 16 (*it)->display(); 17 (*it)->quack(); 18 (*it)->swim(); 19 (*it)->fly(); 20 delete (*it); 21 } 22 } 23 24 int main() 25 { 26 while (true) 27 { 28 test(); 29 } 30 }
稍作解释
main函数中死循环的调用test函数的意图是测试以上实现有没有内存泄露。
Headfirst设计模式的C++实现——策略模式(Strategy)
标签:
原文地址:http://www.cnblogs.com/ren-yu/p/4928809.html