#pragma once
#include "FlyBehavior .h"
class Duck
{
public:
Duck(FlyBehavior* flybh);
virtual ~Duck();
void Swim();
void PerformFly();
virtual void Display() = 0;
private:
FlyBehavior* m_Flybh;
};
#include "Duck.h"
#include <QDeBug>
Duck::Duck(FlyBehavior* flybh)
:m_Flybh(flybh)
{
}
Duck::~Duck()
{
}
void Duck::Swim()
{
qDebug() << "Duck Swim" << endl;
}
//void Duck::Disp()
//{
// qDebug() << "Duck caise" << endl;
//}
void Duck::PerformFly()
{
m_Flybh->Fly();
}
#pragma once
#include "Duck.h"
class RedHeadDuck :
public Duck
{
public:
RedHeadDuck(FlyBehavior* flybh);
~RedHeadDuck();
void Display();
};
#include "RedHeadDuck.h"
#include <QDebug>
RedHeadDuck::RedHeadDuck(FlyBehavior* flybh)
:Duck(flybh)
{
}
RedHeadDuck::~RedHeadDuck()
{
}
void RedHeadDuck::Display()
{
qDebug() << "I'm Red Head Duck" << endl;
}
#pragma once
class FlyBehavior
{
public:
virtual void Fly() = 0;
};
#pragma once
#include "FlyBehavior .h"
class FlyWithWings :
public FlyBehavior
{
public:
FlyWithWings();
~FlyWithWings();
virtual void Fly();
};
#include "FlyWithWings.h"
#include <QDeBug>
FlyWithWings::FlyWithWings()
{
}
FlyWithWings::~FlyWithWings()
{
}
void FlyWithWings::Fly()
{
qDebug() << "wings fly" << endl;
}
#pragma once
#include "FlyBehavior .h"
class FlyWithRun :
public FlyBehavior
{
public:
FlyWithRun();
~FlyWithRun();
virtual void Fly();
};
#include "FlyWithRun.h"
#include <QDeBug>
FlyWithRun::FlyWithRun()
{
}
FlyWithRun::~FlyWithRun()
{
}
void FlyWithRun::Fly()
{
qDebug() << "run fly" << endl;
}
#include "Duck.h"
#include "RedHeadDuck.h"
#include "FlyWithWings.h"
#include "FlyWithRun.h"
//策略模式
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
FlyWithWings* flyWing = new FlyWithWings;
RedHeadDuck rd(flyWing);
rd.Swim();
rd.Display();
rd.PerformFly();
FlyWithRun* flyRun = new FlyWithRun;
RedHeadDuck rd1(flyRun);
rd1.PerformFly();
return a.exec();
}
隔离变化,编程到接口