原则:封装变化的部分;针对超类编程,不针对实现;多组合少继承;

#ifndef __DUCK_H__
#define __DUCK_H__
#include "FlyBehavior.h"
#include "QuackBehavior.h" class Duck
{
public:
Duck()
{ } virtual ~Duck()
{ } virtual void performFly()
{ } virtual void performQuack()
{ } void setQuack(QuackBehavior *t)
{
if (t != NULL)
{
quackBehavior = t;
}
} void setFly(FlyBehavior *t)
{
if (t != NULL)
{
flyBehavior = t;
}
} protected:
QuackBehavior *quackBehavior;
FlyBehavior *flyBehavior;
}; class MuDuck :public Duck
{
public:
MuDuck()
{
quackBehavior = new SqueakQuack();
flyBehavior = new FlyWithWings();
} virtual ~MuDuck()
{
delete quackBehavior;
delete flyBehavior;
} void performFly()
{
flyBehavior->fly();
} void performQuack()
{
quackBehavior->quack();
} };
#endif
#ifndef __QUACKBEHAVIOR_H__
#define __QUACKBEHAVIOR_H__
#include <iostream>
using namespace std; class QuackBehavior
{
public:
QuackBehavior()
{ } virtual void quack() = 0
{ }
}; class MuteQuack : public QuackBehavior
{
public:
MuteQuack()
{ } void quack()
{
cout << "Mute Quack" << endl;
}
}; class SqueakQuack :public QuackBehavior
{
public:
SqueakQuack()
{ } void quack()
{
cout << "Squeak Quack" << endl;
}
}; #endif
#ifndef __FLYBEHAVIOR_H__
#define __FLYBEHAVIOR_H__
#include <iostream>
using namespace std; class FlyBehavior
{
public:
FlyBehavior()
{ } virtual void fly() = 0 {}
}; class FlyWithWings : public FlyBehavior
{
public:
FlyWithWings(){}
void fly()
{
cout << "fly? Yes,I Can!" << endl;
}
}; class FlyNoWay : public FlyBehavior
{
public:
FlyNoWay(){}
void fly()
{
cout << "fly? No! " << endl;
}
}; class FlyRocket :public FlyBehavior
{
public:
FlyRocket()
{ }
void fly()
{
cout << "fly? With Rocket" << endl;
} }; #endif

客户端代码

#include <iostream>
#include "Duck.h"
using namespace std;
int main()
{
Duck *duck = new MuDuck();
duck->performFly();
duck->performQuack(); duck->setFly(new FlyRocket());
duck->performFly(); delete duck; return 0;
}
04-20 17:53