说明:将《Head First设计模式》中策略模式,用C++来实现。
飞翔行为FlyBehavior.h:
#pragma once
#include <iostream>
using namespace std;
class IFlyBehavior
{
public:
virtual ~IFlyBehavior(){}
virtual void Fly() = 0;
};
class CFlyWithWings : public IFlyBehavior
{
public:
void Fly()
{
cout<<"I'm flying"<<endl;
}
};
class CFlyNoWay : public IFlyBehavior
{
public:
void Fly()
{
cout<<"I can't fly"<<endl;
}
};
class CFlyRocketPowered : public IFlyBehavior
{
public:
void Fly()
{
cout<<"I'm flying with a rocket!"<<endl;
}
};
鸣叫行为QuackBehavior.h:
#pragma once
#include <iostream>
using namespace std;
class IQuackBehavior
{
public:
virtual ~IQuackBehavior(){}
virtual void Quack() = 0;
};
class CQuack : public IQuackBehavior
{
public:
void Quack()
{
cout<<"Quack"<<endl;
}
};
class CMuteQuack : public IQuackBehavior
{
public:
void Quack()
{
cout<<"Silence"<<endl;
}
};
class CSqueak : public IQuackBehavior
{
public:
void Quack()
{
cout<<"Squeak"<<endl;
}
};
鸭子类:
#pragma once
#include "FlyBehavior.h"
#include "QuackBehavior.h"
class CDuck
{
public:
CDuck()
: m_pFly(NULL)
, m_pQuack(NULL)
{
}
virtual ~CDuck(){}
virtual void Display() = 0;
void SetFlyBehavior(IFlyBehavior* pFly)
{
m_pFly = pFly;
}
void SetQuackBehavior(IQuackBehavior* pQuack)
{
m_pQuack = pQuack;
}
void PerformFly()
{
if (NULL == m_pFly)
{
return;
}
m_pFly->Fly();
}
void PerformQuack()
{
if (NULL == m_pQuack)
{
return;
}
m_pQuack->Quack();
}
protected:
IFlyBehavior* m_pFly;
IQuackBehavior* m_pQuack;
};
class CMallardDuck : public CDuck
{
public:
CMallardDuck()
{
m_pFly = new CFlyWithWings();
m_pQuack = new CQuack();
}
void Display()
{
cout<<"I'm a real Mallard duck"<<endl;
}
};
class CModelDuck : public CDuck
{
public:
CModelDuck()
{
m_pFly = new CFlyNoWay();
m_pQuack = new CQuack();
}
void Display()
{
cout<<"I'm a model duck"<<endl;
}
};
调用方法:
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
return 1;
}
CDuck* pMallard = new CMallardDuck();
pMallard->PerformQuack();
pMallard->PerformFly();
delete pMallard;
pMallard = NULL;
CDuck* pModel = new CModelDuck();
pModel->PerformFly();
pModel->SetFlyBehavior(new CFlyRocketPowered());
pModel->PerformFly();
delete pModel;
pModel = NULL;
return nRetCode;
}