// test01.cpp : Defines the entry point for the console application.
//
//第一章,设计模式入门,策略模式
#include "stdafx.h"
#include "test01.h"
class FlyBehavior{
public:
virtual void fly(){};
};
class FlyWithWings:public FlyBehavior{
public:
void fly(){
printf("i'm flying!!\n");
}
};
class FlyNoWay : public FlyBehavior
{
public:
void fly(){
printf("i can't fly!\n");
}
};
class QuackBehavior {
public:
virtual void quack() = 0;
};
class Quack:public QuackBehavior
{
public:
Quack(){};
void quack(){
printf("Quack\n");
}
};
class MuteQuack : public QuackBehavior
{
public:
void quack(){
printf("<Silence>");
}
};
class Squeak: public QuackBehavior
{
public:
void quack(){
printf("Squeak");
}
};
class Duck
{
public:
FlyBehavior* flyBehavior;
QuackBehavior* quackBehavior;
Duck(){};
virtual void display(){};
void performFly(){
flyBehavior->fly();
}
void performQuack(){
quackBehavior->quack();
}
void swim(){
printf("All ducks float,even decoys!");
}
//动态设定行为
void setFlyBehavior(FlyBehavior* fb)
{
flyBehavior = fb;
}
void setQuackBehavior(QuackBehavior* qb)
{
quackBehavior = qb;
}
};
class MallardDuck : public Duck
{
public:
MallardDuck()
{
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
}
void display()
{
printf("i'm a real Mallard duck");
}
};
class ModelDuck : public Duck
{
public:
ModelDuck()
{
flyBehavior = new FlyNoWay();
quackBehavior = new Quack();
}
void display(){
printf("i'm a model duck");
}
};
class FlyRocketPowered : public FlyBehavior{
public:
void fly()
{
printf("i'm flying with a rocket!\n");
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Duck* mallard = new MallardDuck();
mallard->performQuack();
mallard->performFly();
Duck* model = new ModelDuck();
model->performFly();
FlyBehavior* fb = new FlyRocketPowered();
model->setFlyBehavior(fb);
model->performFly();
return 0;
}