c++设计模式——策略模式

本文通过实现鸭子的多种飞行行为,展示了策略模式在代码设计中的应用。策略模式允许在运行时选择算法,使代码更具灵活性。文中详细介绍了如何使用策略模式来改变鸭子的飞行方式,包括使用翅膀飞行和跑步飞行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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();
}

    隔离变化,编程到接口

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值