0

I am confused with the concept ? Is it just as simple as incorporating a static method to return the object instead of a constructor ? So that client doesn't need to change the code while we update the library or there is something more to it ?

nexusboy
  • 13
  • 3
  • Can you please write some code example and elaborate bit more? – Gul Ershad Nov 17 '17 at 09:02
  • The answer is that if you do `new X()` you definitely get an instance of the concrete class `X`. A factory method `X.newInstance()` has the freedom in its implementation to create a subclass of `X`. e.g. `public X newInstance() { if( return (Environment.isDebug()) ? new DebuggingX() : new X())` -- but you could have found this anywhere the pattern is discussed e.g. https://en.wikipedia.org/wiki/Factory_method_pattern or any book on OO patterns. – slim Nov 17 '17 at 09:14

1 Answers1

0

The book Head First Design Patterns will be your definitive guide for Java. That is a great book. If you check out my answer to this Stack Overflow Question, you will be able to see my implementation for an ArbitraryPointFactory class in the Point Example code that uses the Factory Method pattern as well as how it differs from Abstract Factory pattern seen in the Point Factory class. Although this answer is presented with C# code samples, the design pattern language I am using to describe their usage, should warrant you an answer.

What you are thinking of in your question is not a design pattern at all. This static method that returns an object to encapsulate the instantiation, is known as the Simple Factory as seen in the Wiki page. The Factory Method pattern more or less abstracts the type being returned via an interface. This is typically done where the sole job of the factory method class is to control creation of the objects for one concrete class that implements the interface being returned. The Abstract Factory provides encapsulation for a group of related products. In my example I was showing for different types of points, however they could implement different interfaces and all use the same Abstract Factory.

The idea is that you are programming to interfaces, not implementations. True factories pull creation logic to a single location in your application and encapsulate the instantiation via interfaces.