Java 工厂模式和策略模式有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/616796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between Factory and Strategy patterns?
提问by Sappidireddy
Can any one explain the difference between factory and strategy patterns?
任何人都可以解释工厂模式和策略模式之间的区别吗?
For me both are looking same other than an extra factory class (which create an object of product in factory patterns)
对我来说,除了一个额外的工厂类(它在工厂模式中创建一个产品对象)之外,两者看起来都一样
采纳答案by tvanfosson
A factory pattern is a creational pattern. A strategy pattern is an operational pattern. Put another way, a factory pattern is used to create objects of a specific type. A strategy pattern is use to perform an operation (or set of operations) in a particular manner. In the classic example, a factory might create different types of Animals: Dog, Cat, Tiger, while a strategy pattern would perform particular actions, for example, Move; using Run, Walk, or Lope strategies.
工厂模式是一种创建模式。策略模式是一种操作模式。换句话说,工厂模式用于创建特定类型的对象。策略模式用于以特定方式执行一个操作(或一组操作)。在经典示例中,工厂可能会创建不同类型的动物:狗、猫、老虎,而策略模式将执行特定操作,例如移动;使用跑步、步行或 Lope 策略。
In fact the two can be used together. For example, you may have a factory that creates your business objects. It may use different strategies based on the persistence medium. If your data is stored locally in XML it would use one strategy. If the data were remote in a different database, it would use another.
其实两者是可以一起使用的。例如,您可能有一个创建业务对象的工厂。它可以根据持久性介质使用不同的策略。如果您的数据本地存储在 XML 中,它将使用一种策略。如果数据在不同的数据库中是远程的,它将使用另一个。
回答by jlembke
The strategy pattern allows you to polymorphically change behavior of a class.
策略模式允许您多态地改变类的行为。
The factory pattern allows you to encapsulate object creation.
工厂模式允许您封装对象创建。
Gary makes a great point. If you are using the principle of coding to abstractions rather than "concretions" then a lot of the patterns start looking like variations on a theme.
加里提出了一个很好的观点。如果您将编码原则用于抽象而不是“具体化”,那么许多模式开始看起来像是主题的变体。
回答by Gary Kephart
Just to add to what tvanfosson said, a lot of the patterns look the same as far as implementation. That is, a lot have you create an interface where perhaps there wasn't one before in your code, and then create a bunch of implementations of that interface. The difference is in their purpose and how they are used.
补充一下 tvanfosson 所说的,就实现而言,很多模式看起来是一样的。也就是说,您创建了一个接口,而您的代码中以前可能没有这个接口,然后创建了该接口的一堆实现。不同之处在于它们的用途和使用方式。
回答by OscarRyz
- The Factory ( method ) Pattern.
- 工厂(方法)模式。
Create concrete instances only. Different arguments may result in different objects. It depends on the logic etc.
仅创建具体实例。不同的参数可能会导致不同的对象。这取决于逻辑等。
- The Strategy Pattern.
- 策略模式。
Encapsulate the algorithm ( steps ) to perform an action. So you can change the strategy and use another algorithm.
封装算法(步骤)以执行操作。所以你可以改变策略并使用另一种算法。
While both look like very similar, the purpose is rather different, one purpose is to create the other is to perform an action.
虽然两者看起来非常相似,但目的却大不相同,一个目的是创建另一个目的是执行一个动作。
So. If your Factory method is fixed, you may have it like this:
所以。如果你的工厂方法是固定的,你可能会像这样:
public Command getCommand( int operatingSystem ) {
switch( operatingSystem ) {
case UNIX :
case LINUX : return new UnixCommand();
case WINDOWS : return new WindowsCommand();
case OSX : return new OSXCommand();
}
}
But suppose your factory needs more advanced or dynamic creation. You may add to the factory method an strategy and change it without having to recompile, the strategy may change at runtime.
但是假设您的工厂需要更高级或动态的创建。您可以向工厂方法添加策略并更改它而无需重新编译,该策略可能会在运行时更改。
回答by OscarRyz
To extend on what Oscar said and in reference to his code:
扩展 Oscar 所说的内容并参考他的代码:
The getCommand is the Factory and the UnixCommand, WindowsCommand and OSXCommand classes are Strategies
getCommand 是 Factory,而 UnixCommand、WindowsCommand 和 OSXCommand 类是 Strategies
回答by Rick B.
I may digress with Oscar in that his example of a Factory implementation is rather tightly coupled and very closed, no wonder your pick is Strategy pattern. A Factory implementation should not depend on any fixed number of specific classes being instantiated, For example:
我可能会离题,因为他的工厂实现示例是相当紧密耦合且非常封闭的,难怪您的选择是策略模式。工厂实现不应依赖于任何固定数量的特定类被实例化,例如:
public Command getCommand( int operatingSystem ) {
return commandTable.get(operatingSystem);
}
...
public class WindowsCommand implements Command {
...
static {
CommandTable.getInstance().registerCommand(WIN_COMMAND_ID, new WindowsCommand());
}
}
I guess the most appropriate criteria to choose one or another is mostly the terms you employ to name your classes and methods, taking into account we all should tend to program to interfaces and not to classes and also focus on the goal: we aim to determine which code will execute on runtime. That said, we can achieve the goal by using any of both patterns.
我想选择一个或另一个最合适的标准主要是你用来命名你的类和方法的术语,考虑到我们都应该倾向于编程接口而不是类,并且还要关注目标:我们的目标是确定哪些代码将在运行时执行。也就是说,我们可以通过使用这两种模式中的任何一种来实现目标。
回答by Brainchild
Strategy and Factory are different purposes. In strategy you have the approach defined, using this pattern you can interchange the behavior (algorithms). Coming to Factory there are lot of variations around. But the original pattern from GO4 states factory leaves creation of object to child class. Here with the factory you are replacing complete instance not the behavior you are interested in. By this you will be replacing complete system not the algorithm.
战略和工厂是不同的目的。在策略中,您定义了方法,使用此模式可以交换行为(算法)。来到工厂,周围有很多变化。但是 GO4 的原始模式声明工厂将对象的创建留给子类。在这里,您正在用工厂替换完整的实例,而不是您感兴趣的行为。这样,您将替换完整的系统而不是算法。
回答by interboy
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.
首先,必须区分简单工厂和抽象工厂。第一个是一个简单的工厂,其中只有一个类充当对象创建的工厂,而在后者中,您连接到工厂接口(定义方法名称),然后调用实现此接口的不同工厂基于某些标准,应该有相同方法的不同实现。例如,我们有一个 ButtonCreationFactory 接口,它由两个工厂实现,第一个 WindowsButtonCreationFactory(创建具有 Windows 外观的按钮)和第二个 LinuxButtonCreationFactory(创建具有 Linux 外观的按钮)。因此,这两个工厂确实具有相同的创建方法和不同的实现(算法)。
For example if you want buttons with Linux look and feel:
例如,如果您想要具有 Linux 外观和感觉的按钮:
ButtonCreationFactory myFactory = new LinuxButtonCreationFactory();
Button button1 = myFactory.createButton(...);
or if you want Windows buttons
或者如果你想要 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.
正是在这种情况下,它产生了一种策略模式,因为它区分了进行某些创建的算法。但是,它在语义上与它不同,因为它用于对象创建而不是操作算法。因此,基本上对于抽象工厂,您可以使用不同的策略创建对象,这使其与策略模式非常相似。然而 AbstractFactory 是创建性的,而 Strategy 模式是可操作的。实施明智,它们的结果是相同的。
回答by user1808932
Factory pattern is a creational pattern, which is created with specified properties(behaviour). while at run time after creation u cn't change it's properties(behaviour). so if u need different properties(behaviour) u have to delete the object and create new object with needed properties(behaviour). which is not gud. while in case of strategy pattern u can change the properties(behaviour) at run time.
工厂模式是一种创建模式,它是用指定的属性(行为)创建的。在创建后的运行时,你不能改变它的属性(行为)。因此,如果您需要不同的属性(行为),则必须删除该对象并创建具有所需属性(行为)的新对象。这不是gud。而在策略模式的情况下,您可以在运行时更改属性(行为)。
回答by user1808932
You cannot understand the difference simply by looking at the code or categorization. To grasp the GoF patterns correctly, look for their intents:
您无法仅通过查看代码或分类来理解差异。要正确掌握 GoF 模式,请寻找它们的意图:
Strategy: "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."
策略:“定义一系列算法,封装每一个,并使它们可以互换。策略让算法独立于使用它的客户端而变化。”
Factory Method: "Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses."
工厂方法:“定义一个用于创建对象的接口,但让子类决定实例化哪个类。工厂方法让一个类将实例化推迟到子类。”
And here's an elaborate explanation about the intents and the differences between these two patterns: Difference between Factory Method and Strategy design patterns
这是关于这两种模式之间的意图和区别的详细解释:工厂方法和策略设计模式之间的区别