?????????????????????塣??????????????????????????滻????????????仯?????????????????
????Head First??????н???????????Duck?????????????????flyBehavior??quackBehavior???????????????????????к??????????????????????flyBehavior??quackBehavior?????????Duck???????????????????????????????????????Duck????????????????????C++??д?????
//MyDuck.h
#ifndef MYDUCK_INCLUDED
#define MYDUCK_INCLUDED
//?????????ó????????????е???
class FlyBehavior{
public:
virtual void fly()=0;
};
class QuackBehavior{
public:
virtual void quack()=0;
};
class FlyWithWings:public FlyBehavior{
public:
void fly();
};
class FlyNoWay:public FlyBehavior{
public:
void fly();
};
class FlyRocketPowerd:public FlyBehavior{
public:
void fly();
};
class Quack:public QuackBehavior{
public:
void quack();
};
class Squeak:public QuackBehavior{
public:
void quack();
};
class MuteQuack:public QuackBehavior{
public:
void quack();
};
class Duck{
public:
Duck();
void swim();
virtual void display()=0;
void performQuack();
void performFly();
void setQuackBehavior(QuackBehavior *newBehavior);
void setFlyBehavior(FlyBehavior *newBehavior);
//???????????????????????е??????????
protected:
FlyBehavior *flyBehavior;
QuackBehavior *quackBehavior;
};
class MallardDuck:public Duck{
public:
virtual void display();
MallardDuck();
};
#endif // MYDUCK_INCLUDED
////MyDuck.cpp
#include "MyDuck"
#include <iostream>
using std::cout;
using std::endl;
//?????????
void FlyWithWings::fly(){
cout<<"I'm flying with wings!!"<<endl;
}
void FlyNoWay::fly(){
cout<<"I can't fly5555!!"<<endl;
}
void FlyRocketPowerd::fly(){
cout<<"I'm flying with a ROCKET!!"<<endl;
}
void Quack::quack(){
cout<<"Quack!!!"<<endl;
}
void Squeak::quack(){
cout<<"Squeak!!!"<<endl;
}
void MuteQuack::quack(){
cout<<"MuteQuack!!!"<<endl;
}
//????Duck?????????
void Duck::swim(){
cout<<"I'm swimming!!!"<<endl;
}
void Duck::performQuack(){
quackBehavior->quack();
}
void Duck::performFly(){
flyBehavior->fly();
}
void Duck::setFlyBehavior(FlyBehavior *newBehavior){
flyBehavior=newBehavior;
}
void Duck::setQuackBehavior(QuackBehavior *newBehavior){
quackBehavior=newBehavior;
}
Duck::Duck(){
}
//????MallardDuck?????????
void MallardDuck::display(){
cout<<"I'm MallardDuck!!!"<<endl;
}
MallardDuck::MallardDuck(){
flyBehavior=new FlyWithWings;
quackBehavior=new Quack;
}
//MyDuckMain.cpp
#include "MyDuck"
int main()
{
Duck *mallard=new MallardDuck;
mallard->display();
mallard->performFly();
mallard->performQuack();
mallard->swim();
mallard->setFlyBehavior(new FlyNoWay);
mallard->performFly();
mallard->setFlyBehavior(new FlyRocketPowerd);
mallard->performFly();
return 0;
}
??????н?????
????I'm MallardDuck!!!
????I'm flying with wings!!
????Quack!!!
????I'm swimming!!!
????I can't fly5555!!
????I'm flying with a ROCKET!!