为什么不是工厂模式排序 [英] Why Not factory Pattern For Sorting

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

问题描述

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

What i want : On 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 thing i should use 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:

这是动态的:

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

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