使用工厂设计模式如何阻止类必须预期必须创建的对象类 [英] How does using the factory design pattern stop a class having to anticipate the class of objects it must create
问题描述
据我了解,工厂设计模式允许通过使用单独的对象来创建对象,其唯一目的是创建第一个对象.可以使用不同类型的工厂来创建不同类型的对象.
As I understand it the factory design pattern allows objects to be created through the use of a separate object that's sole aim is to create the first one. Different types of factory can be used to create different types of object.
我知道这隐藏了主对象的实例化,但是可以肯定的是,它只是被工厂实例化所取代了?
I understand that this hides the instantiation of the primary object however surely this is just replaced by the instantiation of the factory?
此设计模式的一个共同优点是,它停止了一个类,必须预见必须创建的对象的类.但是可以肯定的是,如果工厂应该创建一个特定的类,那么主要类仍然需要预测要使用哪种类型的工厂?
A common advantage for this design pattern is that it stops a class having to anticipate the class of objects it must create. However surely if the factory is supposed to create a specific class the main class still needs to anticipate what kind of factory to use?
我认为我误解了工厂的主要目的?
I assume I'm misunderstanding the main purpose of a factory?
推荐答案
这个问题比看起来要复杂得多,因为工厂的种类很多,因此客户端以不同的方式获取和调用它们.
The question is more complex than it seems, because there are many kinds of factories, so clients obtain and invoke them in different ways.
-
对于静态工厂而言,您是正确的:客户端保留了对工厂课.这样可以将产品类抽象化.因此,通过预期工厂,客户不必预测工厂的确切产量.
In the case of a Static Factory you are correct: the client retains a concrete dependency on a factory class. This allows the product class to be abstracted. So by anticipating the factory, the client doesn't have to anticipate the exact output of the factory.
对于抽象工厂,客户端将其作为依赖项注入,表示应在组合根目录中创建.因此客户既不知道具体的工厂类别,也不知道具体的产品类别.
In the case of an Abstract Factory, the client has it injected as a dependency, which means it should be created in the composition root. So the client knows neither the concrete factory class nor the concrete product classes.
对于工厂方法,客户端是工厂,并为其父母提供具体产品.
In the case of a Factory Method, the client is the factory and provides a concrete product for its parent to consume.
工厂比这三个工厂多,可以用不同的方式调用.但是这三点说明了工厂使用方式之间的巨大差异.
There are more factories than these three, which may be invoked in different ways; but these three show how extreme the differences can be in the way factories are used.
这篇关于使用工厂设计模式如何阻止类必须预期必须创建的对象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!