策略模式

策略模式(Strategy)

定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换.

理解

这里策略与我们平时的意思一致,即可以实现目标的方案集合,在众多方法中选择一种使用.常用于替代if-else,但并非所有情况下都可替代.

优点

可拓展性良好.策略(Strategy)在运行时装载代码,从而解决了有时候支持不使用的方法也是一种性能负担的问题.

缺点

策略类都需要将方法置为public,这导致方法对外暴露,而执行它们是没有意义的.

实现

在购买商品时,常常涉及到折扣,而折扣是多种多样的,每次的折扣选择都不同.也就是说,购买商品这件事是稳定的,选择的折扣是变化的.

失败的设计
#include <iostream>
using namespace std;
#define Discount1 1
#define Discount2 2
#define Discount3 3

class Price {
public:
	void getPrice(int choose) {
		switch (choose){
		case Discount1:
			cout << "打八折!" << endl;
			break;
		case Discount2:
			cout << "满200减50!" << endl;
			break;
		case Discount3:
			cout << "买二送一!" << endl;
			break;
		default:
			break;
		}
	}
};

int main(void) {
	Price price;
	price.getPrice(Discount2);

	system("pause");
	return 0;
}

在这里插入图片描述
可扩展性很差,对新的情况的补充需要寻找该类并更改其内部方法.

成功的设计

在这里插入图片描述

#include <iostream>
using namespace std;

class DiscountStrategy {
public:
	virtual void useDiscount() = 0;
	virtual ~DiscountStrategy(){}
};

class Discount1 : public DiscountStrategy {
public:
	void useDiscount() { cout << "打八折!" << endl; }
};

class Discount2 : public DiscountStrategy {
public:
	void useDiscount() { cout << "满200减50!" << endl; }
};

class Discount3 : public DiscountStrategy {
public:
	void useDiscount() { cout << "买二送一!" << endl; }
};

class Price {
public:
	Price(DiscountStrategy* discount) { m_discount = discount; }
	void getPrice() { m_discount->useDiscount(); }
	~Price() { delete m_discount; }
private:
	DiscountStrategy* m_discount;
};

int main(void) {
	Price price(new Discount2);
	price.getPrice();

	system("pause");
	return 0;
}

在这里插入图片描述
解决了if-else带来的难以拓展的问题.
下一篇:模板模式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值