what's the advantage of using factory method pattern over simple factory?











up vote
3
down vote

favorite












I am reading about factory method pattern and simple factory. turns out As I can understand, simple factory is enough and I don't see the use case of factory method pattern. Please read this link, https://www.binpress.com/factory-design-pattern/ , and I'll ask my questions.



1) in simple factory , it says it's bad because it violates the open/closed principle. I understand that but in factory method pattern what it did still violates the open/closed principle.



if ('car'==$toyName) {
$toy = new NyCar();
} else if ('helicopter'==$toyName) {
$toy = new NyHelicopter();
}


If there'll be a new tory for New York, we need to add it here.



2) after reading the link, before it actually reached the better solution, it used this following code. :



class NySimpleFactory {
public function createToy($toyName) {
$toy = null;

if ('car'==$toyName) {
$toy = new NyCar();
} else if ('helicopter'==$toyName) {
$toy = new NyHelicopter();
}

return $toy;
}
}

class NyToysFactory {

public $simpleFactory;

public function __construct(SimpleFactory $simpleFactory) {
$this->simpleFactory = $simpleFactory;
}

public function produceToy($toyName) {
$toy = null;
$toy = $this->simpleFactory->createToy($toyName);
$toy->prepare();
$toy->package();
$toy->label();
return $toy;
}
}


Then it says,




The developers finish the new code quickly and hand it over to the US
factories. After two weeks, the phone starts ringing in the
developers’ office because the New York factory was having production
issues. It turns out that the NyToysFactory class has been modified by
developers at the remote branch because the staff doesn’t want to do
packaging and labeling work. They’ve modified produceToy() by removing
its label() and package() functions.



It seems like Simple Factory won’t work in this scenario. We don’t
want branches in US to be able to modify produceToy() functions.
ProduceToy() should consist of a set of standard procedures and the
branches should only be responsible for creating location specific
toys. What if they can create an abstract class? And the abstract
class they create will have a concrete produceToy()method which will
implement a set of standard operating procedurea that all branches
have to follow. Inside produceToy(), it calls its own abstract method
createToy() to obtain a toy class. This way createToy() is able to
encapsulate object creation and, since it’s abstract, it delegates the
creation to its subclasses.




Question is: a)What does it mean by saying handing over it to US factories? b) or We don’t want branches in US to be able to modify produceToy() functions. they can still modify produceToy function, what difference does it make at all if they can't or can change it? I just don't understand why simple factory was bad for the following example at all.



No need to read about abstract factory at that link










share|improve this question




























    up vote
    3
    down vote

    favorite












    I am reading about factory method pattern and simple factory. turns out As I can understand, simple factory is enough and I don't see the use case of factory method pattern. Please read this link, https://www.binpress.com/factory-design-pattern/ , and I'll ask my questions.



    1) in simple factory , it says it's bad because it violates the open/closed principle. I understand that but in factory method pattern what it did still violates the open/closed principle.



    if ('car'==$toyName) {
    $toy = new NyCar();
    } else if ('helicopter'==$toyName) {
    $toy = new NyHelicopter();
    }


    If there'll be a new tory for New York, we need to add it here.



    2) after reading the link, before it actually reached the better solution, it used this following code. :



    class NySimpleFactory {
    public function createToy($toyName) {
    $toy = null;

    if ('car'==$toyName) {
    $toy = new NyCar();
    } else if ('helicopter'==$toyName) {
    $toy = new NyHelicopter();
    }

    return $toy;
    }
    }

    class NyToysFactory {

    public $simpleFactory;

    public function __construct(SimpleFactory $simpleFactory) {
    $this->simpleFactory = $simpleFactory;
    }

    public function produceToy($toyName) {
    $toy = null;
    $toy = $this->simpleFactory->createToy($toyName);
    $toy->prepare();
    $toy->package();
    $toy->label();
    return $toy;
    }
    }


    Then it says,




    The developers finish the new code quickly and hand it over to the US
    factories. After two weeks, the phone starts ringing in the
    developers’ office because the New York factory was having production
    issues. It turns out that the NyToysFactory class has been modified by
    developers at the remote branch because the staff doesn’t want to do
    packaging and labeling work. They’ve modified produceToy() by removing
    its label() and package() functions.



    It seems like Simple Factory won’t work in this scenario. We don’t
    want branches in US to be able to modify produceToy() functions.
    ProduceToy() should consist of a set of standard procedures and the
    branches should only be responsible for creating location specific
    toys. What if they can create an abstract class? And the abstract
    class they create will have a concrete produceToy()method which will
    implement a set of standard operating procedurea that all branches
    have to follow. Inside produceToy(), it calls its own abstract method
    createToy() to obtain a toy class. This way createToy() is able to
    encapsulate object creation and, since it’s abstract, it delegates the
    creation to its subclasses.




    Question is: a)What does it mean by saying handing over it to US factories? b) or We don’t want branches in US to be able to modify produceToy() functions. they can still modify produceToy function, what difference does it make at all if they can't or can change it? I just don't understand why simple factory was bad for the following example at all.



    No need to read about abstract factory at that link










    share|improve this question


























      up vote
      3
      down vote

      favorite









      up vote
      3
      down vote

      favorite











      I am reading about factory method pattern and simple factory. turns out As I can understand, simple factory is enough and I don't see the use case of factory method pattern. Please read this link, https://www.binpress.com/factory-design-pattern/ , and I'll ask my questions.



      1) in simple factory , it says it's bad because it violates the open/closed principle. I understand that but in factory method pattern what it did still violates the open/closed principle.



      if ('car'==$toyName) {
      $toy = new NyCar();
      } else if ('helicopter'==$toyName) {
      $toy = new NyHelicopter();
      }


      If there'll be a new tory for New York, we need to add it here.



      2) after reading the link, before it actually reached the better solution, it used this following code. :



      class NySimpleFactory {
      public function createToy($toyName) {
      $toy = null;

      if ('car'==$toyName) {
      $toy = new NyCar();
      } else if ('helicopter'==$toyName) {
      $toy = new NyHelicopter();
      }

      return $toy;
      }
      }

      class NyToysFactory {

      public $simpleFactory;

      public function __construct(SimpleFactory $simpleFactory) {
      $this->simpleFactory = $simpleFactory;
      }

      public function produceToy($toyName) {
      $toy = null;
      $toy = $this->simpleFactory->createToy($toyName);
      $toy->prepare();
      $toy->package();
      $toy->label();
      return $toy;
      }
      }


      Then it says,




      The developers finish the new code quickly and hand it over to the US
      factories. After two weeks, the phone starts ringing in the
      developers’ office because the New York factory was having production
      issues. It turns out that the NyToysFactory class has been modified by
      developers at the remote branch because the staff doesn’t want to do
      packaging and labeling work. They’ve modified produceToy() by removing
      its label() and package() functions.



      It seems like Simple Factory won’t work in this scenario. We don’t
      want branches in US to be able to modify produceToy() functions.
      ProduceToy() should consist of a set of standard procedures and the
      branches should only be responsible for creating location specific
      toys. What if they can create an abstract class? And the abstract
      class they create will have a concrete produceToy()method which will
      implement a set of standard operating procedurea that all branches
      have to follow. Inside produceToy(), it calls its own abstract method
      createToy() to obtain a toy class. This way createToy() is able to
      encapsulate object creation and, since it’s abstract, it delegates the
      creation to its subclasses.




      Question is: a)What does it mean by saying handing over it to US factories? b) or We don’t want branches in US to be able to modify produceToy() functions. they can still modify produceToy function, what difference does it make at all if they can't or can change it? I just don't understand why simple factory was bad for the following example at all.



      No need to read about abstract factory at that link










      share|improve this question















      I am reading about factory method pattern and simple factory. turns out As I can understand, simple factory is enough and I don't see the use case of factory method pattern. Please read this link, https://www.binpress.com/factory-design-pattern/ , and I'll ask my questions.



      1) in simple factory , it says it's bad because it violates the open/closed principle. I understand that but in factory method pattern what it did still violates the open/closed principle.



      if ('car'==$toyName) {
      $toy = new NyCar();
      } else if ('helicopter'==$toyName) {
      $toy = new NyHelicopter();
      }


      If there'll be a new tory for New York, we need to add it here.



      2) after reading the link, before it actually reached the better solution, it used this following code. :



      class NySimpleFactory {
      public function createToy($toyName) {
      $toy = null;

      if ('car'==$toyName) {
      $toy = new NyCar();
      } else if ('helicopter'==$toyName) {
      $toy = new NyHelicopter();
      }

      return $toy;
      }
      }

      class NyToysFactory {

      public $simpleFactory;

      public function __construct(SimpleFactory $simpleFactory) {
      $this->simpleFactory = $simpleFactory;
      }

      public function produceToy($toyName) {
      $toy = null;
      $toy = $this->simpleFactory->createToy($toyName);
      $toy->prepare();
      $toy->package();
      $toy->label();
      return $toy;
      }
      }


      Then it says,




      The developers finish the new code quickly and hand it over to the US
      factories. After two weeks, the phone starts ringing in the
      developers’ office because the New York factory was having production
      issues. It turns out that the NyToysFactory class has been modified by
      developers at the remote branch because the staff doesn’t want to do
      packaging and labeling work. They’ve modified produceToy() by removing
      its label() and package() functions.



      It seems like Simple Factory won’t work in this scenario. We don’t
      want branches in US to be able to modify produceToy() functions.
      ProduceToy() should consist of a set of standard procedures and the
      branches should only be responsible for creating location specific
      toys. What if they can create an abstract class? And the abstract
      class they create will have a concrete produceToy()method which will
      implement a set of standard operating procedurea that all branches
      have to follow. Inside produceToy(), it calls its own abstract method
      createToy() to obtain a toy class. This way createToy() is able to
      encapsulate object creation and, since it’s abstract, it delegates the
      creation to its subclasses.




      Question is: a)What does it mean by saying handing over it to US factories? b) or We don’t want branches in US to be able to modify produceToy() functions. they can still modify produceToy function, what difference does it make at all if they can't or can change it? I just don't understand why simple factory was bad for the following example at all.



      No need to read about abstract factory at that link







      php design-patterns factory-pattern factory-method






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited yesterday









      papiro

      628419




      628419










      asked 2 days ago









      Nika Khurashvili

      5629




      5629
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          2
          down vote













          THIS CODE / PROBLEM does not illuminate the Abstract Factory or Factory Method. Deciding which class to instantiate by switching on a parameter is indeed an anti-pattern encouraging open-closed principle violation.



          Abstract Factory



          The Abstract Factory is all about enforcing a family of related classes:



          abstract class ToyFactory
          + createBear(): ToyBear
          + createElephant(): ToyElephant

          class USToyFactory extends ToyFactory
          + createBear(): ToyBear -> creates USToyBear
          + createElephant(): ToyElephant -> USToyElephant

          abstract class ToyBear
          + playSound()

          class USToyBear extends ToyBear
          + playSound()//play US National Anthem


          Passing a USToyFactory where a ToyFactory is expected enforces the creation of US toys (USToyBear and USToyElephant) – this is the power of Abstract Factory.



          Notice the products, bears, elephants, etc., are known AoT (ahead of time).



          Factory Method



          The Factory Method is all about deferring instantiation to subclasses.



          abstract class Dashboard
          + createWidget(): Widget

          abstract class Widget
          + config()

          class StatsDashboard extends Dashboard
          + createWidget: Widget -> return new StatsWidget()

          class StatsWidget extends Widget


          Calling createWidget() returns a Widget, but which concrete Widget to return must be deferred to subclasses (StatsDashboard returns a StatsWidget).



          Notice the creation methods are declared up the inheritance tree, but they are fulfilled down the inheritance tree.



          ❧ A reader with a keen eye will see that Abstract Factory methods resemble Factory Methods, coincidence? – no. This is where Factory Method’s name is derived (they fulfill concrete class instantiation).



          The confusion regarding “US factories” is valid; this is poor word choice. The author hints this code may be passed around to factory workers which is totally irrelevant and confusing pertaining to the factory patterns.





          To resolve the switch above, you'll need to realize the obvious: each condition handler is related in some way. In this case, they are all toys.



          public function createToy($toyName) {
          $toy = null;

          if ('car'==$toyName) {
          $toy = new NyCar();//I'm a Toy
          } else if ('helicopter'==$toyName) {
          $toy = new NyHelicopter();//I'm a Toy
          }

          return $toy;
          }


          Using polymorphism, we can satisfy the open-closed principle by creating a set of sibling classes:



          abstract class Toy
          + operate()

          Car extends Toy
          Helicopter extends Toy

          some_toy.operate();


          Adding to the switch cases is nothing more than creating another sibling class.



          Dependency injection should be used to instantiate a concrete Toy.



          I hope this helps!






          share|improve this answer























          • Thanks Rafael. LEt's talk about the difference between factory method and simple factory. I can do anything with simple factory, why to use factory method pattern at all?
            – Nika Khurashvili
            2 days ago










          • The Factory Method is about deferring instantiation to subclasses. This is important when you are creating interfaces that create objects but cannot foretell which objects will be created.
            – Rafael
            2 days ago










          • Can we discuss it in a private chat or something? I've learned lot about this pattern but still confuses me somehow. The questions I have will take lots of time here . Thanks in advance
            – Nika Khurashvili
            2 days ago










          • So, instead of using the switch (if/else), and letting createToy choose the subclass, we should pass the sublclass in as an argument and just let createToy instantiate it?
            – papiro
            yesterday






          • 1




            @papiro Instantiation should be handled entirely by DI. After all, how will createToy() know how to create the concrete Toy class? The constructors will likely have different interfaces. In this code example, createToy() is code-smell. Instantiation via DI should be pushed down as far as possible to client code. This dependency is likely fulfillable in a view controller or similar.
            – Rafael
            yesterday













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53372748%2fwhats-the-advantage-of-using-factory-method-pattern-over-simple-factory%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          2
          down vote













          THIS CODE / PROBLEM does not illuminate the Abstract Factory or Factory Method. Deciding which class to instantiate by switching on a parameter is indeed an anti-pattern encouraging open-closed principle violation.



          Abstract Factory



          The Abstract Factory is all about enforcing a family of related classes:



          abstract class ToyFactory
          + createBear(): ToyBear
          + createElephant(): ToyElephant

          class USToyFactory extends ToyFactory
          + createBear(): ToyBear -> creates USToyBear
          + createElephant(): ToyElephant -> USToyElephant

          abstract class ToyBear
          + playSound()

          class USToyBear extends ToyBear
          + playSound()//play US National Anthem


          Passing a USToyFactory where a ToyFactory is expected enforces the creation of US toys (USToyBear and USToyElephant) – this is the power of Abstract Factory.



          Notice the products, bears, elephants, etc., are known AoT (ahead of time).



          Factory Method



          The Factory Method is all about deferring instantiation to subclasses.



          abstract class Dashboard
          + createWidget(): Widget

          abstract class Widget
          + config()

          class StatsDashboard extends Dashboard
          + createWidget: Widget -> return new StatsWidget()

          class StatsWidget extends Widget


          Calling createWidget() returns a Widget, but which concrete Widget to return must be deferred to subclasses (StatsDashboard returns a StatsWidget).



          Notice the creation methods are declared up the inheritance tree, but they are fulfilled down the inheritance tree.



          ❧ A reader with a keen eye will see that Abstract Factory methods resemble Factory Methods, coincidence? – no. This is where Factory Method’s name is derived (they fulfill concrete class instantiation).



          The confusion regarding “US factories” is valid; this is poor word choice. The author hints this code may be passed around to factory workers which is totally irrelevant and confusing pertaining to the factory patterns.





          To resolve the switch above, you'll need to realize the obvious: each condition handler is related in some way. In this case, they are all toys.



          public function createToy($toyName) {
          $toy = null;

          if ('car'==$toyName) {
          $toy = new NyCar();//I'm a Toy
          } else if ('helicopter'==$toyName) {
          $toy = new NyHelicopter();//I'm a Toy
          }

          return $toy;
          }


          Using polymorphism, we can satisfy the open-closed principle by creating a set of sibling classes:



          abstract class Toy
          + operate()

          Car extends Toy
          Helicopter extends Toy

          some_toy.operate();


          Adding to the switch cases is nothing more than creating another sibling class.



          Dependency injection should be used to instantiate a concrete Toy.



          I hope this helps!






          share|improve this answer























          • Thanks Rafael. LEt's talk about the difference between factory method and simple factory. I can do anything with simple factory, why to use factory method pattern at all?
            – Nika Khurashvili
            2 days ago










          • The Factory Method is about deferring instantiation to subclasses. This is important when you are creating interfaces that create objects but cannot foretell which objects will be created.
            – Rafael
            2 days ago










          • Can we discuss it in a private chat or something? I've learned lot about this pattern but still confuses me somehow. The questions I have will take lots of time here . Thanks in advance
            – Nika Khurashvili
            2 days ago










          • So, instead of using the switch (if/else), and letting createToy choose the subclass, we should pass the sublclass in as an argument and just let createToy instantiate it?
            – papiro
            yesterday






          • 1




            @papiro Instantiation should be handled entirely by DI. After all, how will createToy() know how to create the concrete Toy class? The constructors will likely have different interfaces. In this code example, createToy() is code-smell. Instantiation via DI should be pushed down as far as possible to client code. This dependency is likely fulfillable in a view controller or similar.
            – Rafael
            yesterday

















          up vote
          2
          down vote













          THIS CODE / PROBLEM does not illuminate the Abstract Factory or Factory Method. Deciding which class to instantiate by switching on a parameter is indeed an anti-pattern encouraging open-closed principle violation.



          Abstract Factory



          The Abstract Factory is all about enforcing a family of related classes:



          abstract class ToyFactory
          + createBear(): ToyBear
          + createElephant(): ToyElephant

          class USToyFactory extends ToyFactory
          + createBear(): ToyBear -> creates USToyBear
          + createElephant(): ToyElephant -> USToyElephant

          abstract class ToyBear
          + playSound()

          class USToyBear extends ToyBear
          + playSound()//play US National Anthem


          Passing a USToyFactory where a ToyFactory is expected enforces the creation of US toys (USToyBear and USToyElephant) – this is the power of Abstract Factory.



          Notice the products, bears, elephants, etc., are known AoT (ahead of time).



          Factory Method



          The Factory Method is all about deferring instantiation to subclasses.



          abstract class Dashboard
          + createWidget(): Widget

          abstract class Widget
          + config()

          class StatsDashboard extends Dashboard
          + createWidget: Widget -> return new StatsWidget()

          class StatsWidget extends Widget


          Calling createWidget() returns a Widget, but which concrete Widget to return must be deferred to subclasses (StatsDashboard returns a StatsWidget).



          Notice the creation methods are declared up the inheritance tree, but they are fulfilled down the inheritance tree.



          ❧ A reader with a keen eye will see that Abstract Factory methods resemble Factory Methods, coincidence? – no. This is where Factory Method’s name is derived (they fulfill concrete class instantiation).



          The confusion regarding “US factories” is valid; this is poor word choice. The author hints this code may be passed around to factory workers which is totally irrelevant and confusing pertaining to the factory patterns.





          To resolve the switch above, you'll need to realize the obvious: each condition handler is related in some way. In this case, they are all toys.



          public function createToy($toyName) {
          $toy = null;

          if ('car'==$toyName) {
          $toy = new NyCar();//I'm a Toy
          } else if ('helicopter'==$toyName) {
          $toy = new NyHelicopter();//I'm a Toy
          }

          return $toy;
          }


          Using polymorphism, we can satisfy the open-closed principle by creating a set of sibling classes:



          abstract class Toy
          + operate()

          Car extends Toy
          Helicopter extends Toy

          some_toy.operate();


          Adding to the switch cases is nothing more than creating another sibling class.



          Dependency injection should be used to instantiate a concrete Toy.



          I hope this helps!






          share|improve this answer























          • Thanks Rafael. LEt's talk about the difference between factory method and simple factory. I can do anything with simple factory, why to use factory method pattern at all?
            – Nika Khurashvili
            2 days ago










          • The Factory Method is about deferring instantiation to subclasses. This is important when you are creating interfaces that create objects but cannot foretell which objects will be created.
            – Rafael
            2 days ago










          • Can we discuss it in a private chat or something? I've learned lot about this pattern but still confuses me somehow. The questions I have will take lots of time here . Thanks in advance
            – Nika Khurashvili
            2 days ago










          • So, instead of using the switch (if/else), and letting createToy choose the subclass, we should pass the sublclass in as an argument and just let createToy instantiate it?
            – papiro
            yesterday






          • 1




            @papiro Instantiation should be handled entirely by DI. After all, how will createToy() know how to create the concrete Toy class? The constructors will likely have different interfaces. In this code example, createToy() is code-smell. Instantiation via DI should be pushed down as far as possible to client code. This dependency is likely fulfillable in a view controller or similar.
            – Rafael
            yesterday















          up vote
          2
          down vote










          up vote
          2
          down vote









          THIS CODE / PROBLEM does not illuminate the Abstract Factory or Factory Method. Deciding which class to instantiate by switching on a parameter is indeed an anti-pattern encouraging open-closed principle violation.



          Abstract Factory



          The Abstract Factory is all about enforcing a family of related classes:



          abstract class ToyFactory
          + createBear(): ToyBear
          + createElephant(): ToyElephant

          class USToyFactory extends ToyFactory
          + createBear(): ToyBear -> creates USToyBear
          + createElephant(): ToyElephant -> USToyElephant

          abstract class ToyBear
          + playSound()

          class USToyBear extends ToyBear
          + playSound()//play US National Anthem


          Passing a USToyFactory where a ToyFactory is expected enforces the creation of US toys (USToyBear and USToyElephant) – this is the power of Abstract Factory.



          Notice the products, bears, elephants, etc., are known AoT (ahead of time).



          Factory Method



          The Factory Method is all about deferring instantiation to subclasses.



          abstract class Dashboard
          + createWidget(): Widget

          abstract class Widget
          + config()

          class StatsDashboard extends Dashboard
          + createWidget: Widget -> return new StatsWidget()

          class StatsWidget extends Widget


          Calling createWidget() returns a Widget, but which concrete Widget to return must be deferred to subclasses (StatsDashboard returns a StatsWidget).



          Notice the creation methods are declared up the inheritance tree, but they are fulfilled down the inheritance tree.



          ❧ A reader with a keen eye will see that Abstract Factory methods resemble Factory Methods, coincidence? – no. This is where Factory Method’s name is derived (they fulfill concrete class instantiation).



          The confusion regarding “US factories” is valid; this is poor word choice. The author hints this code may be passed around to factory workers which is totally irrelevant and confusing pertaining to the factory patterns.





          To resolve the switch above, you'll need to realize the obvious: each condition handler is related in some way. In this case, they are all toys.



          public function createToy($toyName) {
          $toy = null;

          if ('car'==$toyName) {
          $toy = new NyCar();//I'm a Toy
          } else if ('helicopter'==$toyName) {
          $toy = new NyHelicopter();//I'm a Toy
          }

          return $toy;
          }


          Using polymorphism, we can satisfy the open-closed principle by creating a set of sibling classes:



          abstract class Toy
          + operate()

          Car extends Toy
          Helicopter extends Toy

          some_toy.operate();


          Adding to the switch cases is nothing more than creating another sibling class.



          Dependency injection should be used to instantiate a concrete Toy.



          I hope this helps!






          share|improve this answer














          THIS CODE / PROBLEM does not illuminate the Abstract Factory or Factory Method. Deciding which class to instantiate by switching on a parameter is indeed an anti-pattern encouraging open-closed principle violation.



          Abstract Factory



          The Abstract Factory is all about enforcing a family of related classes:



          abstract class ToyFactory
          + createBear(): ToyBear
          + createElephant(): ToyElephant

          class USToyFactory extends ToyFactory
          + createBear(): ToyBear -> creates USToyBear
          + createElephant(): ToyElephant -> USToyElephant

          abstract class ToyBear
          + playSound()

          class USToyBear extends ToyBear
          + playSound()//play US National Anthem


          Passing a USToyFactory where a ToyFactory is expected enforces the creation of US toys (USToyBear and USToyElephant) – this is the power of Abstract Factory.



          Notice the products, bears, elephants, etc., are known AoT (ahead of time).



          Factory Method



          The Factory Method is all about deferring instantiation to subclasses.



          abstract class Dashboard
          + createWidget(): Widget

          abstract class Widget
          + config()

          class StatsDashboard extends Dashboard
          + createWidget: Widget -> return new StatsWidget()

          class StatsWidget extends Widget


          Calling createWidget() returns a Widget, but which concrete Widget to return must be deferred to subclasses (StatsDashboard returns a StatsWidget).



          Notice the creation methods are declared up the inheritance tree, but they are fulfilled down the inheritance tree.



          ❧ A reader with a keen eye will see that Abstract Factory methods resemble Factory Methods, coincidence? – no. This is where Factory Method’s name is derived (they fulfill concrete class instantiation).



          The confusion regarding “US factories” is valid; this is poor word choice. The author hints this code may be passed around to factory workers which is totally irrelevant and confusing pertaining to the factory patterns.





          To resolve the switch above, you'll need to realize the obvious: each condition handler is related in some way. In this case, they are all toys.



          public function createToy($toyName) {
          $toy = null;

          if ('car'==$toyName) {
          $toy = new NyCar();//I'm a Toy
          } else if ('helicopter'==$toyName) {
          $toy = new NyHelicopter();//I'm a Toy
          }

          return $toy;
          }


          Using polymorphism, we can satisfy the open-closed principle by creating a set of sibling classes:



          abstract class Toy
          + operate()

          Car extends Toy
          Helicopter extends Toy

          some_toy.operate();


          Adding to the switch cases is nothing more than creating another sibling class.



          Dependency injection should be used to instantiate a concrete Toy.



          I hope this helps!







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited yesterday

























          answered 2 days ago









          Rafael

          4,24372037




          4,24372037












          • Thanks Rafael. LEt's talk about the difference between factory method and simple factory. I can do anything with simple factory, why to use factory method pattern at all?
            – Nika Khurashvili
            2 days ago










          • The Factory Method is about deferring instantiation to subclasses. This is important when you are creating interfaces that create objects but cannot foretell which objects will be created.
            – Rafael
            2 days ago










          • Can we discuss it in a private chat or something? I've learned lot about this pattern but still confuses me somehow. The questions I have will take lots of time here . Thanks in advance
            – Nika Khurashvili
            2 days ago










          • So, instead of using the switch (if/else), and letting createToy choose the subclass, we should pass the sublclass in as an argument and just let createToy instantiate it?
            – papiro
            yesterday






          • 1




            @papiro Instantiation should be handled entirely by DI. After all, how will createToy() know how to create the concrete Toy class? The constructors will likely have different interfaces. In this code example, createToy() is code-smell. Instantiation via DI should be pushed down as far as possible to client code. This dependency is likely fulfillable in a view controller or similar.
            – Rafael
            yesterday




















          • Thanks Rafael. LEt's talk about the difference between factory method and simple factory. I can do anything with simple factory, why to use factory method pattern at all?
            – Nika Khurashvili
            2 days ago










          • The Factory Method is about deferring instantiation to subclasses. This is important when you are creating interfaces that create objects but cannot foretell which objects will be created.
            – Rafael
            2 days ago










          • Can we discuss it in a private chat or something? I've learned lot about this pattern but still confuses me somehow. The questions I have will take lots of time here . Thanks in advance
            – Nika Khurashvili
            2 days ago










          • So, instead of using the switch (if/else), and letting createToy choose the subclass, we should pass the sublclass in as an argument and just let createToy instantiate it?
            – papiro
            yesterday






          • 1




            @papiro Instantiation should be handled entirely by DI. After all, how will createToy() know how to create the concrete Toy class? The constructors will likely have different interfaces. In this code example, createToy() is code-smell. Instantiation via DI should be pushed down as far as possible to client code. This dependency is likely fulfillable in a view controller or similar.
            – Rafael
            yesterday


















          Thanks Rafael. LEt's talk about the difference between factory method and simple factory. I can do anything with simple factory, why to use factory method pattern at all?
          – Nika Khurashvili
          2 days ago




          Thanks Rafael. LEt's talk about the difference between factory method and simple factory. I can do anything with simple factory, why to use factory method pattern at all?
          – Nika Khurashvili
          2 days ago












          The Factory Method is about deferring instantiation to subclasses. This is important when you are creating interfaces that create objects but cannot foretell which objects will be created.
          – Rafael
          2 days ago




          The Factory Method is about deferring instantiation to subclasses. This is important when you are creating interfaces that create objects but cannot foretell which objects will be created.
          – Rafael
          2 days ago












          Can we discuss it in a private chat or something? I've learned lot about this pattern but still confuses me somehow. The questions I have will take lots of time here . Thanks in advance
          – Nika Khurashvili
          2 days ago




          Can we discuss it in a private chat or something? I've learned lot about this pattern but still confuses me somehow. The questions I have will take lots of time here . Thanks in advance
          – Nika Khurashvili
          2 days ago












          So, instead of using the switch (if/else), and letting createToy choose the subclass, we should pass the sublclass in as an argument and just let createToy instantiate it?
          – papiro
          yesterday




          So, instead of using the switch (if/else), and letting createToy choose the subclass, we should pass the sublclass in as an argument and just let createToy instantiate it?
          – papiro
          yesterday




          1




          1




          @papiro Instantiation should be handled entirely by DI. After all, how will createToy() know how to create the concrete Toy class? The constructors will likely have different interfaces. In this code example, createToy() is code-smell. Instantiation via DI should be pushed down as far as possible to client code. This dependency is likely fulfillable in a view controller or similar.
          – Rafael
          yesterday






          @papiro Instantiation should be handled entirely by DI. After all, how will createToy() know how to create the concrete Toy class? The constructors will likely have different interfaces. In this code example, createToy() is code-smell. Instantiation via DI should be pushed down as far as possible to client code. This dependency is likely fulfillable in a view controller or similar.
          – Rafael
          yesterday




















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53372748%2fwhats-the-advantage-of-using-factory-method-pattern-over-simple-factory%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Volksrepublik China

          How to test boost logger output in unit testing?

          Write to the output between two pipeline