策略设计模式和工厂方法设计模式 [英] Strategy Design Pattern and Factory Method Design Pattern

查看:146
本文介绍了策略设计模式和工厂方法设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习设计模式。现在我明白了一点,但对我来说有很多的混乱。 策略DP 工厂方法DP 之间有什么区别?对于我来说,他们都看起来是一样的。

解决方案

策略是关于行为。工厂是关于创造/控制的。



假设你有算法来计算折扣百分比。您可以拥有该算法的2个实现;一个用于普通客户,一个用于普通的好客户。

您可以使用策略DP进行此实现:您创建一个界面,以及2个实现该界面的类。在一个类中,您实现常规折扣计算算法,在另一个类中实现好客户算法。



然后,您可以使用工厂模式实例化你想要的类。因此,工厂方法实例化了常规客户折扣算法或其他实现。



简而言之:工厂方法实例化正确的类;策略实现包含必须执行的算法。


I start learning Design Patterns. Now I understand a little bit but there are quite a lot of confusions for me. What's the difference between Strategy DP and Factory Method DP? For me they both looks like the same.

解决方案

Strategy is about behavior. Factory is about creation/instatation.

Suppose you have an algorithm, to calculate a discount percentage. You can have 2 implementations of that algorithm; one for regular customers, and one for extra-ordinary good customers.
You can use a strategy DP for this implementation: you create an interface, and 2 classes that implement that interface. In one class, you implement the regular discount-calculation algorithm, in the other class you implement the 'good customers' algorithm.

Then, you can use a factory pattern to instantiate the class that you want. The factory method thus instantiates either the regular customer-discount algorithm, or the other implementation.

In short: the factory method instantiates the correct class; the strategy implementation contains the algorithm that must be executed.

这篇关于策略设计模式和工厂方法设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆