有人能解释一下工厂模式和战略模式之间的区别吗?
对于我来说,两者看起来是一样的,除了一个额外的工厂类(在工厂模式中创建一个product对象)
有人能解释一下工厂模式和战略模式之间的区别吗?
对于我来说,两者看起来是一样的,除了一个额外的工厂类(在工厂模式中创建一个product对象)
当前回答
工厂模式和策略模式之间的关键区别是在哪里进行操作。工厂模式对创建的对象执行操作(工厂类在创建后完成工作),而策略模式对上下文类本身执行操作。
若要将工厂模式更改为策略模式,则不从工厂类返回创建的对象,将对象保存在上下文类中,并在上下文类中创建包装器方法来执行操作,而不是直接从创建的对象执行操作。
虽然有人可能会问我们是否可以对创建的对象进行操作,但为什么我们仍然需要在上下文类中创建包装器呢?好的,关键是操作。策略模式可以根据策略改变操作,而且不需要改变对象,可以依靠上下文对象来做不同的操作,而不需要改变对象本身。
其他回答
只是补充一下tvanfosson所说的,就实现而言,很多模式看起来都是一样的。也就是说,很多时候你创建了一个接口,而在你的代码中可能没有,然后创建了该接口的一堆实现。区别在于它们的目的和使用方式。
Factory(和Factory返回的FactoryMethod):
创建型模式 基于继承 工厂返回一个工厂方法(接口),该方法返回具体对象 你可以用新的具体对象代替接口,客户端(调用者)不应该知道所有的具体实现 客户端始终只访问接口,您可以在Factory方法中隐藏对象创建细节
看看这篇维基百科和javarevisited的文章
策略模式:
这是一种行为模式 它是基于委派的 它通过修改方法行为来改变对象的内容 它用来在一系列算法之间切换 它在运行时改变对象的行为
例子:
您可以为特定的项目(机票或购物车项目)配置折扣策略。在本例中,您将在7月至12月期间提供25%的折扣,而在1月至6月期间不提供折扣。
相关文章:
策略模式的真实例子
设计模式:工厂vs工厂方法vs抽象工厂
战略和工厂是不同的目的。在策略中,您已经定义了方法,使用此模式可以交换行为(算法)。来到工厂有很多变化。但是GO4状态工厂的原始模式将对象的创建留给了子类。这里用工厂替换的是完整的实例,而不是你感兴趣的行为。这样你将取代整个系统,而不是算法。
根据奥斯卡的说法和他的准则:
getCommand是工厂类,UnixCommand、WindowsCommand和OSXCommand类是策略类
First of all a difference between simple factory and abstract factory must be made. The first one is a simple factory where you only have one class which acts as a factory for object creation, while in the latter you connect to an factory interface (which defines the method names) and then call the different factories that implement this interface which are supposed to have different implementations of the same method based on some criteria. For example, we have a ButtonCreationFactory interface, which is implemented by two factories, the first WindowsButtonCreationFactory (creates buttons with Windows look and feel) and the second LinuxButtonCreationFactory (creates buttons with Linux look and feel). So both these factories do have the same creation method with different implementations (algorithms). You can reference this in runtime based on the method that you type of button that you want.
例如,如果你想要带有Linux外观和感觉的按钮:
ButtonCreationFactory myFactory = new LinuxButtonCreationFactory();
Button button1 = myFactory.createButton(...);
或者你想要Windows按钮
ButtonCreationFactory myFactory = new WindowsButtonCreationFactory();
Button button1 = myFactory.createButton(...);
Exactly in this case, it results in a kind of strategy pattern, since it differentiates algorithms for doing some creation. However, it differs from it semantically because it is used for OBJECT CREATION rather than operational algorithms. So, basically with abstract factory you have object creation using different strategies, which makes it very similar to the strategy pattern. However the AbstractFactory is creational, while the Strategy pattern is operational. Implementation wise, they result to be the same.