<p>When is it a good idea to use factory methods within an object instead of a Factory class?</p>

[{'answer_id': 69861, 'author': 'Brad Wilson', 'author_id': 1554, 'author_profile': 'https://Stackoverflow.com/users/1554', 'pm_score': 3, 'selected': False, 'text': "<p>It's really a matter of taste. Factory classes can be abstracted/interfaced away as necessary, whereas factory methods are lighter weight (and also tend to be testable, since they don't have a defined type, but they will require a well-known registration point, akin to a service locator but for locating factory methods).</p>\n"}, {'answer_id': 70179, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 2, 'selected': False, 'text': "<p>Factory classes are useful for when the object type that they return has a private constructor, when different factory classes set different properties on the returning object, or when a specific factory type is coupled with its returning concrete type. </p>\n\n<p><strong>WCF</strong> uses ServiceHostFactory classes to retrieve ServiceHost objects in different situations. The standard ServiceHostFactory is used by IIS to retrieve ServiceHost instances for <em>.svc</em> files, but a WebScriptServiceHostFactory is used for services that return serializations to JavaScript clients. ADO.NET Data Services has its own special  DataServiceHostFactory and ASP.NET has its  ApplicationServicesHostFactory since its services have private constructors.</p>\n\n<p>If you only have one class that's consuming the factory, then you can just use a factory method within that class.</p>\n"}, {'answer_id': 70298, 'author': 'jonfm', 'author_id': 6924, 'author_profile': 'https://Stackoverflow.com/users/6924', 'pm_score': 0, 'selected': False, 'text': '<p>Factory classes are more heavyweight, but give you certain advantages. In cases when you need to build your objects from multiple, raw data sources they allow you to encapsulate only the building logic (and maybe the aggregation of the data) in one place. There it can be tested in abstract without being concerned with the object interface.</p>\n\n<p>I have found this a useful pattern, particularly where I am unable to replace and inadequate ORM and want to efficiently instantiate many objects from DB table joins or stored procedures.</p>\n'}, {'answer_id': 71394, 'author': 'Rik', 'author_id': 5409, 'author_profile': 'https://Stackoverflow.com/users/5409', 'pm_score': 4, 'selected': False, 'text': '<p>They\'re also useful when you need several "constructors" with the same parameter type but with different behavior. </p>\n'}, {'answer_id': 399988, 'author': 'Rasmus Faber', 'author_id': 5542, 'author_profile': 'https://Stackoverflow.com/users/5542', 'pm_score': 7, 'selected': False, 'text': "<p>Factory methods should be considered as an alternative to constructors - mostly when constructors aren't expressive enough, ie.</p>\n\n<pre><code>class Foo{\n  public Foo(bool withBar);\n}\n</code></pre>\n\n<p>is not as expressive as:</p>\n\n<pre><code>class Foo{\n  public static Foo withBar();\n  public static Foo withoutBar();\n}\n</code></pre>\n\n<p>Factory classes are useful when you need a complicated process for constructing the object, when the construction need a dependency that you do not want for the actual class, when you need to construct different objects etc.</p>\n"}, {'answer_id': 2430719, 'author': 'kyoryu', 'author_id': 129175, 'author_profile': 'https://Stackoverflow.com/users/129175', 'pm_score': 9, 'selected': False, 'text': "<p>I like thinking about design pattens in terms of my classes being 'people,' and the patterns are the ways that the people talk to each other.</p>\n\n<p>So, to me the factory pattern is like a hiring agency.  You've got someone that will need a variable number of workers.  This person may know some info they need in the people they hire, but that's it.</p>\n\n<p>So, when they need a new employee, they call the hiring agency and tell them what they need.  Now, to actually <em>hire</em> someone, you need to know a lot of stuff - benefits, eligibility verification, etc.  But the person  hiring doesn't need to know any of this - the hiring agency handles all of that.</p>\n\n<p>In the same way, using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want.</p>\n\n<pre><code>public interface IThingFactory\n{\n    Thing GetThing(string theString);\n}\n\npublic class ThingFactory : IThingFactory\n{\n    public Thing GetThing(string theString)\n    {\n        return new Thing(theString, firstDependency, secondDependency);\n    }\n}\n</code></pre>\n\n<p>So, now the consumer of the ThingFactory can get a Thing, without having to know about the dependencies of the Thing, except for the string data that comes from the consumer.</p>\n"}, {'answer_id': 10559506, 'author': 'Mahn', 'author_id': 1329367, 'author_profile': 'https://Stackoverflow.com/users/1329367', 'pm_score': 7, 'selected': False, 'text': '<p>One situation where I personally find separate Factory classes to make sense is when the final object you are trying to create relies on several other objects. E.g, in PHP: Suppose you have a <code>House</code> object, which in turn has a <code>Kitchen</code> and a <code>LivingRoom</code> object, and the <code>LivingRoom</code> object has a <code>TV</code> object inside as well. </p>\n\n<p>The simplest method to achieve this is having each object create their children on their construct method, but if the properties are relatively nested, when your <code>House</code> fails creating you will probably spend some time trying to isolate exactly what is failing.</p>\n\n<p>The alternative is to do the following (dependency injection, if you like the fancy term):</p>\n\n<pre class="lang-php prettyprint-override"><code>$TVObj = new TV($param1, $param2, $param3);\n$LivingroomObj = new LivingRoom($TVObj, $param1, $param2);\n$KitchenroomObj = new Kitchen($param1, $param2);\n$HouseObj = new House($LivingroomObj, $KitchenroomObj);\n</code></pre>\n\n<p>Here if the process of creating a <code>House</code> fails there is only one place to look, but having to use this chunk every time one wants a new <code>House</code> is far from convenient. Enter the Factories:</p>\n\n<pre class="lang-php prettyprint-override"><code>class HouseFactory {\n    public function create() {\n        $TVObj = new TV($param1, $param2, $param3);\n        $LivingroomObj = new LivingRoom($TVObj, $param1, $param2);\n        $KitchenroomObj = new Kitchen($param1, $param2);\n        $HouseObj = new House($LivingroomObj, $KitchenroomObj);\n\n        return $HouseObj;\n    }\n}\n\n$houseFactory = new HouseFactory();\n$HouseObj = $houseFactory-&gt;create();\n</code></pre>\n\n<p>Thanks to the factory here the process of creating a <code>House</code> is abstracted (in that you don\'t need to create and set up every single dependency when you just want to create a <code>House</code>) and at the same time centralized which makes it easier to maintain. There are other reasons why using separate Factories can be beneficial (e.g. testability) but I find this specific use case to illustrate best how Factory classes can be useful.</p>\n'}, {'answer_id': 17668707, 'author': 'Prakash Chhipa', 'author_id': 2251992, 'author_profile': 'https://Stackoverflow.com/users/2251992', 'pm_score': 4, 'selected': False, 'text': '<p>It is important to clearly differentiate the idea behind using factory or factory method.\nBoth are meant to address mutually exclusive different kind of object creation problems.</p>\n\n<p>Let\'s be specific about "factory method":</p>\n\n<p>First thing is that, when you are developing library or APIs which in turn will be used for further application development, then factory method is one of the best selections for creation pattern. Reason behind; <strong>We know that when to create an object of required functionality(s) but type of object will remain undecided or it will be decided ob dynamic parameters being passed</strong>.</p>\n\n<p>Now the point is, approximately same can be achieved by using factory pattern itself but one huge drawback will introduce into the system if factory pattern will be used for above highlighted problem, it is that your logic of crating different objects(sub classes objects) will be specific to some business condition so in future when you need to extend your library\'s functionality for other platforms(In more technically, you need to add more sub classes of basic interface or abstract class so factory will return those objects also in addition to existing one based on some dynamic parameters) then every time you need to change(extend) the logic of factory class which will be costly operation and not good from design perspective.\nOn the other side, if "factory method" pattern will be used to perform the same thing then you just need to create additional functionality(sub classes) and get it registered dynamically by injection which doesn\'t require changes in your base code.</p>\n\n<pre class="lang-java prettyprint-override"><code>interface Deliverable \n{\n    /*********/\n}\n\nabstract class DefaultProducer \n{\n\n    public void taskToBeDone() \n    {   \n        Deliverable deliverable = factoryMethodPattern();\n    }\n    protected abstract Deliverable factoryMethodPattern();\n}\n\nclass SpecificDeliverable implements Deliverable \n{\n /***SPECIFIC TASK CAN BE WRITTEN HERE***/\n}\n\nclass SpecificProducer extends DefaultProducer \n{\n    protected Deliverable factoryMethodPattern() \n    {\n        return new SpecificDeliverable();\n    }\n}\n\npublic class MasterApplicationProgram \n{\n    public static void main(String arg[]) \n    {\n        DefaultProducer defaultProducer = new SpecificProducer();\n        defaultProducer.taskToBeDone();\n    }\n}\n</code></pre>\n'}, {'answer_id': 27735620, 'author': 'Robert', 'author_id': 1798677, 'author_profile': 'https://Stackoverflow.com/users/1798677', 'pm_score': 0, 'selected': False, 'text': "<p>I liken factories to the concept of libraries. For example you can have a library for working with numbers and another for working with shapes. You can store the functions of these libraries in logically named directories as <code>Numbers</code> or <code>Shapes</code>. These are generic types that could include integers, floats, dobules, longs or rectangles, circles, triangles, pentagons in the case of shapes.</p>\n\n<p>The factory petter uses polymorphism, dependency injection and Inversion of control.</p>\n\n<p>The stated purpose of the Factory Patterns is: <code>Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.</code></p>\n\n<p>So let's say that you are building an Operating System or Framework and you are building all the discrete components.</p>\n\n<p>Here is a simple example of the concept of the Factory Pattern in PHP. I may not be 100% on all of it but it's intended to serve as a simple example. I am not an expert.</p>\n\n<pre><code>class NumbersFactory {\n    public static function makeNumber( $type, $number ) {\n        $numObject = null;\n        $number = null;\n\n        switch( $type ) {\n            case 'float':\n                $numObject = new Float( $number );\n                break;\n            case 'integer':\n                $numObject = new Integer( $number );\n                break;\n            case 'short':\n                $numObject = new Short( $number );\n                break;\n            case 'double':\n                $numObject = new Double( $number );\n                break;\n            case 'long':\n                $numObject = new Long( $number );\n                break;\n            default:\n                $numObject = new Integer( $number );\n                break;\n        }\n\n        return $numObject;\n    }\n}\n\n/* Numbers interface */\nabstract class Number {\n    protected $number;\n\n    public function __construct( $number ) {\n        $this-&gt;number = $number;\n    }\n\n    abstract public function add();\n    abstract public function subtract();\n    abstract public function multiply();\n    abstract public function divide();\n}\n/* Float Implementation */\nclass Float extends Number {\n    public function add() {\n        // implementation goes here\n    }\n\n    public function subtract() {\n        // implementation goes here\n    }\n\n    public function multiply() {\n        // implementation goes here\n    }\n\n    public function divide() {\n        // implementation goes here\n    }\n}\n/* Integer Implementation */\nclass Integer extends Number {\n    public function add() {\n        // implementation goes here\n    }\n\n    public function subtract() {\n        // implementation goes here\n    }\n\n    public function multiply() {\n        // implementation goes here\n    }\n\n    public function divide() {\n        // implementation goes here\n    }\n}\n/* Short Implementation */\nclass Short extends Number {\n    public function add() {\n        // implementation goes here\n    }\n\n    public function subtract() {\n        // implementation goes here\n    }\n\n    public function multiply() {\n        // implementation goes here\n    }\n\n    public function divide() {\n        // implementation goes here\n    }\n}\n/* Double Implementation */\nclass Double extends Number {\n    public function add() {\n        // implementation goes here\n    }\n\n    public function subtract() {\n        // implementation goes here\n    }\n\n    public function multiply() {\n        // implementation goes here\n    }\n\n    public function divide() {\n        // implementation goes here\n    }\n}\n/* Long Implementation */\nclass Long extends Number {\n    public function add() {\n        // implementation goes here\n    }\n\n    public function subtract() {\n        // implementation goes here\n    }\n\n    public function multiply() {\n        // implementation goes here\n    }\n\n    public function divide() {\n        // implementation goes here\n    }\n}\n\n$number = NumbersFactory::makeNumber( 'float', 12.5 );\n</code></pre>\n"}, {'answer_id': 30465141, 'author': 'Dzianis Yafimau', 'author_id': 3877717, 'author_profile': 'https://Stackoverflow.com/users/3877717', 'pm_score': 4, 'selected': False, 'text': "<p>It is good idea to use <strong>factory methods</strong> inside object when:</p>\n\n<ol>\n<li>Object's class doesn't know what exact sub-classes it have to create</li>\n<li>Object's class is designed so that objects it creates were specified by sub-classes</li>\n<li>Object's class delegates its duties to auxiliary sub-classes and doesn't know what exact class will take these duties</li>\n</ol>\n\n<p>It is good idea to use <strong>abstract factory</strong> class when:</p>\n\n<ol>\n<li>Your object shouldn't depend on how its inner objects are created and designed</li>\n<li>Group of linked objects should be used together and you need to serve this constraint</li>\n<li>Object should be configured by one of several possible families of linked objects that will be a part of your parent object</li>\n<li>It is required to share child objects showing interfaces only but not an implementation</li>\n</ol>\n"}, {'answer_id': 32471927, 'author': 'Muhammad Awais', 'author_id': 4296800, 'author_profile': 'https://Stackoverflow.com/users/4296800', 'pm_score': 2, 'selected': False, 'text': "<p>Consider a scenario when you have to design an Order and Customer class. For simplicity and initial requirements you do not feel need of factory for Order class and fill your application with many 'new Order()' statements. Things are working well.</p>\n\n<p>Now a new requirement comes into picture that Order object cannot be instantiated without Customer association (new dependency). Now You have following considerations.</p>\n\n<p>1- You create constructor overload which will work only for new implementations. (Not acceptable).\n2- You change Order() signatures and change each and every invokation. (Not a good practice and real pain).</p>\n\n<p>Instead If you have created a factory for Order Class you only have to change one line of code and you are good to go. I suggest Factory class for almost every aggregate association. Hope that helps.</p>\n"}, {'answer_id': 35857241, 'author': 'Ravindra babu', 'author_id': 4999394, 'author_profile': 'https://Stackoverflow.com/users/4999394', 'pm_score': 4, 'selected': False, 'text': '<p>UML from </p>\n\n<p><a href="https://i.stack.imgur.com/LUIor.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/LUIor.gif" alt="enter image description here"></a></p>\n\n<p><em>Product:</em> It defines an interface of the objects the Factory method creates.</p>\n\n<p><em>ConcreteProduct:</em> Implements Product interface</p>\n\n<p><em>Creator:</em> Declares the Factory method</p>\n\n<p><em>ConcreateCreator:</em>  Implements the Factory method to return an instance of a ConcreteProduct</p>\n\n<p><strong>Problem statement:</strong> Create a Factory of Games by using Factory Methods, which defines the game interface.</p>\n\n<p>Code snippet:</p>\n\n<pre class="lang-java prettyprint-override"><code>import java.util.HashMap;\n\n\n/* Product interface as per UML diagram */\ninterface Game{\n    /* createGame is a complex method, which executes a sequence of game steps */\n    public void createGame();\n}\n\n/* ConcreteProduct implementation as per UML diagram */\nclass Chess implements Game{\n    public Chess(){\n\n    }\n    public void createGame(){\n        System.out.println("---------------------------------------");\n        System.out.println("Create Chess game");\n        System.out.println("Opponents:2");\n        System.out.println("Define 64 blocks");\n        System.out.println("Place 16 pieces for White opponent");\n        System.out.println("Place 16 pieces for Black opponent");\n        System.out.println("Start Chess game");\n        System.out.println("---------------------------------------");\n    }\n}\nclass Checkers implements Game{\n    public Checkers(){\n\n    }\n    public void createGame(){\n        System.out.println("---------------------------------------");\n        System.out.println("Create Checkers game");\n        System.out.println("Opponents:2 or 3 or 4 or 6");\n        System.out.println("For each opponent, place 10 coins");\n        System.out.println("Start Checkers game");\n        System.out.println("---------------------------------------");\n    }\n}\nclass Ludo implements Game{\n    public Ludo(){\n\n    }\n    public void createGame(){\n        System.out.println("---------------------------------------");\n        System.out.println("Create Ludo game");\n        System.out.println("Opponents:2 or 3 or 4");\n        System.out.println("For each opponent, place 4 coins");\n        System.out.println("Create two dices with numbers from 1-6");\n        System.out.println("Start Ludo game");\n        System.out.println("---------------------------------------");\n    }\n}\n\n/* Creator interface as per UML diagram */\ninterface IGameFactory {\n    public Game getGame(String gameName);\n}\n\n/* ConcreteCreator implementation as per UML diagram */\nclass GameFactory implements IGameFactory {\n\n     HashMap&lt;String,Game&gt; games = new HashMap&lt;String,Game&gt;();\n    /*  \n        Since Game Creation is complex process, we don\'t want to create game using new operator every time.\n        Instead we create Game only once and store it in Factory. When client request a specific game, \n        Game object is returned from Factory instead of creating new Game on the fly, which is time consuming\n    */\n\n    public GameFactory(){\n\n        games.put(Chess.class.getName(),new Chess());\n        games.put(Checkers.class.getName(),new Checkers());\n        games.put(Ludo.class.getName(),new Ludo());        \n    }\n    public Game getGame(String gameName){\n        return games.get(gameName);\n    }\n}\n\npublic class NonStaticFactoryDemo{\n    public static void main(String args[]){\n        if ( args.length &lt; 1){\n            System.out.println("Usage: java FactoryDemo gameName");\n            return;\n        }\n\n        GameFactory factory = new GameFactory();\n        Game game = factory.getGame(args[0]);\n        if ( game != null ){                    \n            game.createGame();\n            System.out.println("Game="+game.getClass().getName());\n        }else{\n            System.out.println(args[0]+  " Game does not exists in factory");\n        }           \n    }\n}\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>java NonStaticFactoryDemo Chess\n---------------------------------------\nCreate Chess game\nOpponents:2\nDefine 64 blocks\nPlace 16 pieces for White opponent\nPlace 16 pieces for Black opponent\nStart Chess game\n---------------------------------------\nGame=Chess\n</code></pre>\n\n<p>This example shows a <code>Factory</code> class by implementing a <code>FactoryMethod</code>.</p>\n\n<ol>\n<li><p><code>Game</code> is the interface for all type of games. It defines complex method: <code>createGame()</code></p></li>\n<li><p><code>Chess, Ludo, Checkers</code> are different variants of games, which provide implementation to <code>createGame()</code></p></li>\n<li><p><code>public Game getGame(String gameName)</code> is <code>FactoryMethod</code> in <code>IGameFactory</code> class</p></li>\n<li><p><code>GameFactory</code> pre-creates different type of games in constructor. It implements <code>IGameFactory</code> factory method. </p></li>\n<li><p>game Name is passed as command line argument to <code>NotStaticFactoryDemo</code></p></li>\n<li><p><code>getGame</code> in <code>GameFactory</code> accepts a game name and returns corresponding <code>Game</code> object.</p></li>\n</ol>\n\n<p><strong>Factory:</strong></p>\n\n<blockquote>\n  <p>Creates objects without exposing the instantiation logic to the client.</p>\n</blockquote>\n\n<p><strong>FactoryMethod</strong></p>\n\n<blockquote>\n  <p>Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses</p>\n</blockquote>\n\n<p><strong>Use case:</strong></p>\n\n<p>When to use: <code>Client</code> doesn\'t know what concrete classes it will be required to create at runtime, but just wants to get a class that will do the job.</p>\n'}, {'answer_id': 45575361, 'author': 'Samet ÖZTOPRAK', 'author_id': 6717610, 'author_profile': 'https://Stackoverflow.com/users/6717610', 'pm_score': 1, 'selected': False, 'text': '<p>if you want to create a different object in terms of using. It is useful.</p>\n\n<pre><code>public class factoryMethodPattern {\n      static String planName = "COMMERCIALPLAN";\n      static int units = 3;\n      public static void main(String args[]) {\n          GetPlanFactory planFactory = new GetPlanFactory();\n          Plan p = planFactory.getPlan(planName);\n          System.out.print("Bill amount for " + planName + " of  " + units\n                        + " units is: ");\n          p.getRate();\n          p.calculateBill(units);\n      }\n}\n\nabstract class Plan {\n      protected double rate;\n\n      abstract void getRate();\n\n      public void calculateBill(int units) {\n            System.out.println(units * rate);\n      }\n}\n\nclass DomesticPlan extends Plan {\n      // @override\n      public void getRate() {\n            rate = 3.50;\n      }\n}\n\nclass CommercialPlan extends Plan {\n      // @override\n      public void getRate() {\n            rate = 7.50;\n      }\n}\n\nclass InstitutionalPlan extends Plan {\n      // @override\n      public void getRate() {\n            rate = 5.50;\n      }\n}\n\nclass GetPlanFactory {\n\n      // use getPlan method to get object of type Plan\n      public Plan getPlan(String planType) {\n            if (planType == null) {\n                  return null;\n            }\n            if (planType.equalsIgnoreCase("DOMESTICPLAN")) {\n                  return new DomesticPlan();\n            } else if (planType.equalsIgnoreCase("COMMERCIALPLAN")) {\n                  return new CommercialPlan();\n            } else if (planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {\n                  return new InstitutionalPlan();\n            }\n            return null;\n      }\n}\n</code></pre>\n'}, {'answer_id': 49159679, 'author': 'nits.kk', 'author_id': 504133, 'author_profile': 'https://Stackoverflow.com/users/504133', 'pm_score': 1, 'selected': False, 'text': '<p>Any class deferring the object creation to its sub class for the object it needs to work with can be seen as an example of Factory pattern.</p>\n\n<p>I have mentioned in detail in an another answer at <a href="https://stackoverflow.com/a/49110001/504133">https://stackoverflow.com/a/49110001/504133</a></p>\n'}, {'answer_id': 59073313, 'author': 'tagus', 'author_id': 6081899, 'author_profile': 'https://Stackoverflow.com/users/6081899', 'pm_score': 1, 'selected': False, 'text': '<p>I think it will depend of loose coupling degree that you want to bring to your code.</p>\n\n<p>Factory method decouples things very well but factory class no.</p>\n\n<p>In other words, it\'s easier to change things if you use factory method than if you use a simple factory (known as factory class).</p>\n\n<p>Look into this example: <a href="https://connected2know.com/programming/java-factory-pattern/" rel="nofollow noreferrer">https://connected2know.com/programming/java-factory-pattern/</a> . Now, imagine that you want to bring a new Animal. In Factory class you need to change the Factory but in the factory method, no, you only need to add a new subclass. </p>\n'}, {'answer_id': 68110309, 'author': 'Mykola Tokariev', 'author_id': 10220374, 'author_profile': 'https://Stackoverflow.com/users/10220374', 'pm_score': -1, 'selected': False, 'text': '<p><a href="https://i.stack.imgur.com/wAQvR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wAQvR.png" alt="enter image description here" /></a>\nImagine you have a different customers with different preferences. Someone need Volkswagen another one Audi and so on. One thing is common - it\'s a car.</p>\n<p>To make our customer happy we need a factory. The factory only should know which car the customer want and will deliver such car to customer. If later we have some another car we can easily extend our car park and our factory.</p>\n<p>Below you can see an example (ABAP):\n<a href="https://i.stack.imgur.com/i2AFy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i2AFy.png" alt="enter image description here" /></a></p>\n<p>Now we will create an instance of the factory and listening for the customers wishes.\n<a href="https://i.stack.imgur.com/tUNVw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tUNVw.png" alt="enter image description here" /></a></p>\n<p>We created three different cars with only one create( ) method.</p>\n<p>Result:</p>\n<p><a href="https://i.stack.imgur.com/6WM4W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6WM4W.png" alt="enter image description here" /></a></p>\n<p>Quite often is factory pattern very usefull if you want to make the logic more clean and the program more extensible.</p>\n'}, {'answer_id': 70043790, 'author': 'Krasimir', 'author_id': 642670, 'author_profile': 'https://Stackoverflow.com/users/642670', 'pm_score': 0, 'selected': False, 'text': "<p>My short explanation will be that we use the factory pattern when we don't have enough information to create a concrete object. We either don't know the dependencies or we don't know the type of the object. And almost always we don't know them because this is information that comes at runtime.</p>\n<p>Example: we know that we have to create a vehicle object but we don't know if it flies or it works on ground.</p>\n"}, {'answer_id': 71321528, 'author': 'Lunatic', 'author_id': 15758781, 'author_profile': 'https://Stackoverflow.com/users/15758781', 'pm_score': 2, 'selected': False, 'text': '<p><strong>GOF</strong> Definition :</p>\n<p>Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.</p>\n<p><strong>Generic</strong>  example :</p>\n<pre><code>public abstract class Factory&lt;T&gt; {\n\n    public abstract T instantiate(Supplier&lt;? extends T&gt; supplier);\n\n}\n</code></pre>\n<p>The concrete class</p>\n<pre><code>public class SupplierFactory&lt;T&gt; extends Factory&lt;T&gt; {\n\n    @Override\n    public T instantiate(Supplier&lt;? extends T&gt; supplier) {\n        return supplier.get();\n    }\n}\n</code></pre>\n<p>The Implementation</p>\n<pre><code>public class Alpha implements BaseInterface {\n    @Override\n    public void doAction() {\n        System.out.println(&quot;The Alpha executed&quot;);\n    }\n}\n\npublic class Beta implements BaseInterface {\n    @Override\n    public void doAction() {\n        System.out.println(&quot;The Beta executed&quot;);\n    }\n}\n\npublic interface BaseInterface {\n    void doAction();\n}\n\npublic class Main {\n    public static void main(String[] args) {\n        Factory&lt;BaseInterface&gt; secondFactory = new SupplierFactory&lt;&gt;();\n        secondFactory.instantiate(Beta::new).doAction();\n        secondFactory.instantiate(Alpha::new).doAction();\n    }\n}\n</code></pre>\n<p><strong>Brief</strong> advantages</p>\n<ul>\n<li>You are separating code that can vary from the code that does not vary (i.e., the advantages of using a simple factory pattern is still present). This technique helps you easily maintain code.</li>\n<li>Your code is not tightly coupled; so, you can add new classes like Lion, Beer, and so forth, at any time in the system without modifying the existing architecture. So, you have followed the “closed for modification but open for extension” principle.</li>\n</ul>\n'}]
['https://Stackoverflow.com/questions/69849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']