我正在使用据称使用工厂模式的 java 代码,但我并不完全相信该模式。
我的代码是这样做的:
// the factory
class SomeFactoryImpl {
Set<SomeClass> getSomeListOfObjects();
}
在代码中的某个地方:
{ ...
SomeFactory factory = new SomeFactoryImpl();
Set<SomeClass> list = factory.getSomeListOfObjects();
}
我正在思考的一点是,如果工厂类没有静态 create() 方法,那么将需要实例化一个工厂,这IMO 应该和实例化对象本身一样复杂。
我认为这样的工厂可以返回要生成的对象集合的论点还不够好。 我觉得如果在实际从工厂创建对象之前需要创建工厂实例,那么可以有更干净的解决方法。
我觉得create方法最好是工厂类的静态方法。 但我也确信我的观点并不完全“正确”。
那么 SO 社区能否举例说明实例化 Factory 对象比使用静态创建方法更好?
另外,我遇到了类似问题的答案,其中列出了这些链接和答案:所以我需要清楚地了解 FactoryMethodPattern、FactoryMethod 和 CreationMethod 以及代码示例。
I was working with java code that is supposedly using the Factory pattern, but I'm not completely convinced by the pattern.
My code does this:
// the factory
class SomeFactoryImpl {
Set<SomeClass> getSomeListOfObjects();
}
And somewhere in the code:
{ ...
SomeFactory factory = new SomeFactoryImpl();
Set<SomeClass> list = factory.getSomeListOfObjects();
}
The point I'm pondering is, if factory classes don't have a static create() method, then one will need to instantiate a factory, which IMO should be just as complex as instantiating an object itself.
I don't consider the argument that such a factory can return collections of objects to be produced is good enough. I feel there can be cleaner workarounds, if a factory instance needs to be created before actually creating objects from the factory.
I feel that it is better if the create method a static method of the factory class. But I'm also sure that my opinion is not completely "correct".
So can the SO community give examples where instantiating a Factory object is better than using static create methods?
Also, I came across an answer to a similar question, which listed these links and the answer: so I need to know clearly the difference between FactoryMethodPattern, FactoryMethod and CreationMethod with code examples.
发布评论
评论(5)
使用工厂实例与依赖注入结合使用可以带来真正的好处。
因此,在您的示例中,而不是:
您将:
然后稍后...
几点:
我知道这只能解决你问题的一部分......
Using an instance of a factory shows the real benefits when combined with dependency injection.
So in your example, instead of:
You would have:
then later...
Some points:
I know this only addresses a subset of your question...
我想,用于创建对象的静态方法是最流行的方法,但也有一些用例首先创建工厂实例是有意义的。 例如,如果您想将其与注册表结合起来(应允许多个注册表共存)。
另外,如果工厂依赖于一些动态上下文信息(数据库连接等),我认为最好让工厂实例来处理这个问题。
I guess, a static method for the object creation is the most popular approach, but there are also some use-cases where first creating a factory instance makes sense. For example if you want to combine it with a registry (where multiple registries should be allowed to co-exist).
Also if the factory relies on some dynamic context information (database connections, ...) it is in my opinion better to let a factory-instance handle this.
首先你忘记了工厂模式的主要目的,我打开了四人帮的书,它写道:
“定义一个用于创建对象的接口,但让子类决定实例化哪个类。工厂方法让一个类将实例化推迟到子类。”
这意味着您实际上定义了一个接口,因此
SomeFactoryImpl
实际上应该实现在其他地方定义的接口。 当您有许多需要实例化的对象但您不想关心它们是什么类型的对象时,这会很方便。例如,我使用它们开发了一个远程 Swing 应用程序,其中客户端通过序列化下载客户端虚拟机中不存在的一些类的定义。 每个类都定义了 JPanel 的一个子类,它具有特定的视图,但是当到达客户端时,我必须找到一种方法来实例化这些类而不知道它们,所以我使用工厂模式来调用工厂类并让它实例化我的未知对象(尽管它正在扩展我定义的 JPanel 的子类)。另一个例子是生成特定于案例的对象以满足您的需求。 例如(如与此设计模式相关的维基百科页面中所述),您可以认为一个工厂构建对象,然后是另一个构建同一类型对象的工厂,但用于生成“假对象”,这将无法通过某种单元测试。
但是,您也可以使用静态方法解决您的特定问题,但请考虑将生成项目的部分与在大项目中使用它们的部分分开。 当然,开发客户端部分的人应该只知道使用了哪个工厂接口,并且知道这一点才能使用其他部分中定义的所有对象。
创建模式是一种“工具”模式,仅用于定义构造函数的自定义版本,而不必担心使用标准定义(方法的名称等于类的名称),但它没什么特别的。 只是实例化对象的不同方式。创建模式实际上并不能解决任何类型的特定问题(不包括具有相同数量和类型参数的构造函数)。
First of all you are forgetting the main aim of the factory pattern, I opened the book of the gang of four and it states:
"Define an interface for creating an objet, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses."
This means that actually you define an interface, so
SomeFactoryImpl
should actually implement an interface defined somewhere else. This comes handy when you've got many objects that need to be instantiated but you don't want to care about which kind of object they are.. For example I used them to develop a remote swing application in which the client downloaded through serialization the definition of some classes that didn't exist in the client VM. Every class defined a subclass of JPanel which its specific view but when reaching the client I had to find a way to istantiate these classes without knowing them so I used a factory pattern to call the factory class and let it instantiate my uknown object (althrough it is extending a subclass of JPanel defined by me).Another example would be the generation of case-specific object to suit your needs. For example (like stated in wikipedia page related to this design pattern) you can think a factory that builds object and then another factory for the same kind of object but used to generate "fake objects" that will fail some kind of unit testing.
However you can solve your specific problem with static methods too but think about splitting the part that generates items from the part that uses them in a big project. Of course who is developing the client part should just know which factory interface is used and know just this to use all the objects definet in the other part.
Creation Pattern is a sort of 'facility' pattern used just to define custom versions of constructors without worrying using standard definition (having the name of the method equal to the name of the class) but it's nothing special. Just a different way to istantiate objects.. the creation pattern actually doesn't solve any kind of specific problem (excluding constructors with same number and kind of arguments).
这就是为什么我创建工厂对象的实例,
RedWidgetFactory
、BlueWidgetFactory
不同。 该配置与所创建的对象类型正交,Here's why I create instances of factory objects
RedWidgetFactory
,BlueWidgetFactory
. The configuration is orthogonal to the type(s) of objects being createdIMO,您拥有的代码确实是 GoF 的正确样本抽象工厂模式,即使它的使用并不完全优化。 如果我没记错的话,GoF 书描述了工厂(SomeFactory、SomeFactoryImpl)和产品(SomeClass)之间的关系,但没有提及实例化工厂的细节。
如果您拥有的是不会被广泛使用的内部 API,那么您拥有的可能就足够了。 否则,您可以:
如果选择#1,我个人通常会尝试在 JDBC 之后对其进行建模,其中:
Driver
将是抽象工厂Connections
、Statements
等是productsDriverManager
(GoF 书中未明确指定)是一个实用程序类,它根据传入的 JDBC URL 为您选择一个工厂(在本例中,
DriverManager
继续执行)并为您创建产品,如果您像大多数人一样使用getConnection(...)
方法。)为了将其与您的问题联系起来,可以通过调用
But 作为您的方法 来使用 JDBC指出,这是次优的,并且在某种程度上违背了使用抽象工厂模式的目的。
这个问题曾经也让我很困扰,直到有一天我意识到该模式实际上并没有明确谈论工厂是如何创建的。
我希望这回答了你的问题。
IMO, the code you have is indeed a proper specimen of the GoF Abstract Factory pattern, even if its use is not completely optimal. If I recall correctly, the GoF book describes the relationship between factories (SomeFactory, SomeFactoryImpl) and products (SomeClass) but leaves the specifics of instantiating factories open.
If what you have is an internal API that isn't going to be widely used, what you have is probably sufficient. Otherwise, you could:
If going with #1, I personally usually try and model it after JDBC, where:
Driver
would be the abstract factoryConnections
,Statements
etc are productsDriverManager
(not specified in GoF book explicitly) is the utility class that selects a factory for you based on the JDBC URL passed in(In this case, the
DriverManager
goes ahead and creates the product for you also, if you use thegetConnection(...)
methods, as most do.)To tie it back to your question, one could arguably use JDBC by calling
But as your pointed out, this is sub-optimal, and somewhat defeats the purpose of using the abstract factory pattern.
This problem used to bother me a lot too, until I realized one day that that pattern actually does not explicitly talk about how factories are created.
I hope this answers your question.