简体   繁体   中英

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. But why it is not common to create an instance of the Factory class using new Factory() and then calling the req getObj method? 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? 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 .

You should read 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. So it can be used both ways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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