简体   繁体   English

工厂方法,为什么我们使用静态调用从工厂获取对象

[英]Factory method, why we use a static call to get the object from factory

As far my understanding goes while using the factory method we used to get the object by calling a static method of the factory .. like Foo f = Factory.getObj() .. the method is made static as we do not need to create an object before calling the getObj method which will actually return my desired concrete object. 到目前为止,我的理解是使用工厂方法,我们通过调用工厂的静态方法来获取对象..就像Foo f = Factory.getObj() ..方法是静态的,因为我们不需要创建一个在调用getObj方法之前的对象,该方法实际上将返回我想要的具体对象。 But why it is not common to create an instance of the Factory class using new Factory() and then calling the req getObj method? 但是为什么使用new Factory()然后调用req getObj方法创建Factory类的实例并不常见? Sorry if this sound foolish but why it is common to make the factory method as static? 对不起,如果这听起来很愚蠢,但为什么将工厂方法设为静态是很常见的?

Also is static factory and factory are two different thing? 静电厂和工厂也是两回事吗?

You have to ask yourself: 你必须问自己:

Will different objects of Factory class behave differently? Factory类的不同对象会有不同的表现吗? In this case, will they create new objects in a different manner? 在这种情况下,他们会以不同的方式创建新对象吗?

The answer is No . 答案是否定的 If a method is not object scoped , its a perfect candidate for static . 如果方法不是对象作用域 ,则它是static的完美候选者。

You should read Effective Java Item 1: Consider static factory methods instead of constructors . 您应该阅读Effective Java Item 1: Consider static factory methods instead of constructors There is a detailed explanation there. 那里有详细的解释。 Also, classical Factory Method design pattern http://en.wikipedia.org/wiki/Factory_method_pattern is not static. 此外,经典的工厂方法设计模式http://en.wikipedia.org/wiki/Factory_method_pattern不是静态的。 So it can be used both ways. 所以它可以两种方式使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM