8.策略模式

  策略模式是指定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。也就是说这些算法所完成的功能一样,对外的接口一样,只是各自实现上存在差异。用策略模式来封装算法,效果比较好。

           

#include <iostream>
using namespace std;

// 排序算法抽象类
class AbstractSortAlgorithm
{
public:
	virtual void choose_sort() = 0;
};

// 冒泡排序
class BubbleSort : public AbstractSortAlgorithm
{
public:
	void choose_sort()
	{
		cout << "使用冒泡排序" << endl;
	}
};

// 快排
class QuickSort : public AbstractSortAlgorithm
{
public:
	void choose_sort()
	{
		cout << "使用快排" << endl;
	}
};


// 排序算法选择策略
class Strategy
{
public:
	Strategy(AbstractSortAlgorithm* sort)
	{
		pSort = sort;
	}
	~Strategy()
	{
		delete pSort;
	}

	void choose()
	{
		pSort->choose_sort();
	}

private:
	AbstractSortAlgorithm* pSort;
};

void test_01()
{
	Strategy* sort = new Strategy(new BubbleSort);
	sort->choose();

	cout << "-------------" << endl;

	sort = new Strategy(new QuickSort);
	sort->choose();
}

int main()
{
	test_01();

	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值