What is a Factory Design Pattern in PHP?

后端 未结 9 1031
清歌不尽
清歌不尽 2020-11-27 10:15

This confuses me, in the most simplest terms what does it do? Pretend you are explaining to your mother or someone almost please.

9条回答
  •  没有蜡笔的小新
    2020-11-27 10:59

    For the record, in easy words, a factory like @Pindatjuh said, returns a object.

    So, what's the difference with a constructor? (that does the same)

    1. a constructor uses his own instance.
    2. Something i want to so something more advanced and i don't want to bloat the object (or add dependencies).
    3. Constructor is called when each instance is created. Sometimes you don't want that.

      For example, let's say that every time i creates an object of the class Account, i read from the database a file and use it as a template.

    Using constructor:

    class Account {
          var $user;
          var $pwd;
          var ...
          public __construct() {
             // here i read from the file
             // and many other stuff
          }
    }
    

    Using factory:

    class Account {
          var $user;
          var $pwd;
          var ...
    }
    class AccountFactory {
          public static Create() {
             $obj=new Account();
             // here we read the file and more stuff.
             return $obj;
          }
    

提交回复
热议问题