标签:
策略模式:定义了算法族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
#ifndef DUCK_H #define DUCK_H #include "FlyBehavior.h" #include "QuackBehavior.h" class Duck { public: void swim(); virtual void display() = 0 ; void performFly() { flyBehavior->fly(); } void performQuack() { quackBehavior->quack(); } void setFlyBehavior(FlyBehavior* fly) { flyBehavior = fly; } void setQuackBehavior(QuackBehavior* quack) { quackBehavior = quack; } public: FlyBehavior* flyBehavior; QuackBehavior* quackBehavior; }; #endifDuck.h
#ifndef MALLARDDUCK_H #define MALLARDDUCK_H #include "Duck.h" #include "FlyBehavior.h" #include "FlyWithWings.h" #include "Quack.h" #include "QuackBehavior.h" #include <iostream> class MallardDuck : public Duck { public: MallardDuck() { flyBehavior = new FlyWithWings; quackBehavior = new Quack; } virtual void display() { std::cout<<"I‘m mallard duck!"<<std::endl; } }; #endif
#ifndef REDHEADDUCK_H #define REDHEADDUCK_H #include "Duck.h" #include "Squeak.h" #include "FlyWithWings.h" #include <iostream> class RedheadDuck : public Duck { public: RedheadDuck() { quackBehavior = new Squeak; flyBehavior = new FlyWithWings; } virtual display() { std::cout<<"I‘m red head duck!"<<std::endl; } } #endif
#ifndef QUACKBEHAVIOR_H #define QUACKBEHAVIOR_H class QuackBehavior { public: virtual void quack() = 0; }; #endif
#ifndef QUACK_H #define QUACK_H #include "QuackBehavior.h" #include <iostream> class Quack : public QuackBehavior { public: void quack() { std::cout<<"guagua jiao!"<<std::endl; } }; #endif
#ifndef SQUEAK_H #define SQUEAK_H #include "QuackBehavior.h" #include <iostream> class Squeak : public QuackBehavior { public: void quack() { std::cout<<"zhizhi jiao!"<<std::endl; } }; #endif
#ifndef MUTEQUACK_H #define MUTEQUACK_H #include "QuackBehavior.h" #include <iostream> class MuteQuack : public QuackBehavior { public: void quack() { std::cout<<"buhui jiao!"<<std::endl; } }; #endif
#ifndef FLYBEHAVIOR_H #define FLYBEHAVIOR_H class FlyBehavior { public: virtual void fly() = 0; }; #endif
#ifndef FLYNOWAY_H #define FLYNOWAY_H #include "FlyBehavior.h" #include <iostream> class FlyNoWay : public FlyBehavior { public: void fly() { std::cout<<"Fly no way!"<<std::endl; } }; #endif
#ifndef FLYWITHWINGS_H #define FLYWITHWINGS_H #include "FlyBehavior.h" #include <iostream> class FlyWithWings : public FlyBehavior { public: void fly() { std::cout<<"Fly with wings!"<<std::endl; } }; #endif
#include "MallardDuck.h" #include "Duck.h" #include "FlyNoWay.h" int main() { Duck* md = new MallardDuck(); md->performFly(); md->setFlyBehavior(new FlyNoWay); md->performFly(); return 1; }
标签:
原文地址:http://www.cnblogs.com/lisiyuannnn/p/4742385.html