为什么不使用Factory模式进行排序? [英] Why not Factory pattern for sorting?

查看:75
本文介绍了为什么不使用Factory模式进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行时,根据用户的行为和历史记录,我需要执行排序操作。就我而言, SortByDate / SortByDemand / SortByConsumption 只会返回字符串,或者我们可以说order by子句(可能很复杂)。

At run time, based on user behavior and history, I need to perform a sorting operation. In my case, SortByDate/SortByDemand/SortByConsumption will just return the string, or we can say order by clause(which can be complex).

在大多数论坛中,我发现应该使用策略模式进行排序。

In most of the forums, I have found Strategy pattern should be used for sorting.

我在此处附加了用于战略模式的图像。 Util类将调用三个类之一的对象,即SortByDate / SortByDemand / SortByConsumption

I have attached the image for Strategy pattern here. Util class will call the object of one the three classes i.e SortByDate/SortByDemand/SortByConsumption

因此,每次定义新的排序方法时,我都需要更改util类并定义新策略。

So every time a new method of sorting is defined, I need to change the util class and define a new Strategy.

但是,如果我使用工厂实现它,则util类只需要调用工厂,它将处理要调用的类。因此,我认为我应该使用工厂。

If however I implemented it using factory, the util class just need to call the factory and it will take care of which class to call. So I think I should use factory.

不过,我读过策略是满足此类需求的最佳模式。为什么这里的策略模式更好?

However I have read that strategy is best pattern for such needs. Why is strategy pattern is better here?

推荐答案

策略是一种模式,旨在允许您添加新的(根据情况排序)无需破坏算法客户端的软件。这是对设计复杂性的一项投资,如果您需要添加新算法而不破坏客户,这将是有回报的。 Factory是一种补充策略的模式,因为算法实现的客户不应该明确知道他们使用的是哪种实现(就软件类别而言)。工厂实例化了算法的具体实现,因此客户可以在不知道细节的情况下使用它们。

Strategy is a pattern aimed at allowing you to add new (in your case sort) algorithms to your software without breaking the clients of the algorithms. It's an investment in design complexity that will pay off if you need to add new algorithms without breaking your clients. Factory is a pattern that complements Strategy because the clients of the algorithm implementations should not know specifically which implementation they're using (in terms of software classes). The factory instantiates the concrete implementations of the algorithm so the client can use them without knowing the details.

这是静态结构:

Here's the static structure:

这是动态的地方:

这篇关于为什么不使用Factory模式进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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