Simple Factory Pattern ):
It is also called the Static Factory Method mode, which belongs to the class creation mode. In simple factory mode, instances of different classes can be returned based on different parameters. In simple factory mode, a class is defined specifically to create instances of other classes. the created instances usually share a common parent class.
The simple factory mode includes the following roles:
Factory: The Factory role. the Factory role is responsible for implementing the internal logic of creating all instances.
Product: abstract Product role. the abstract Product role is the parent class of all created objects and describes the common public interfaces of all instances.
ConcreteProduct: a specific product role. the specific product role is the creation target. all created objects act as instances of a specific class of this role.
UML diagram:
Disadvantages of the simple factory model
1. because the factory class integrates the creation logic of all products, the entire system will be affected once it fails to work normally.
2. Using the simple factory mode will increase the number of classes in the system and increase the complexity and difficulty of understanding the system in a certain program.
3. it is difficult to expand the system. once a new product is added, the factory logic has to be modified. if there are many product types, the factory logic may be too complicated, which is not conducive to system expansion and maintenance.
4. in simple factory mode, the factory role cannot form a hierarchy based on inheritance because the static factory method is used.
Abstract class Fruit {} class Apple extends Fruit {function _ construct () {echo "Apple" ;}} class Banana extends Fruit {function _ construct () {echo "Banana" ;}} class Factory {static function fruit ($ classname) {if ($ classname = "Apple") {return new Apple ();} else if ($ classname = "Banana") {return new Banana ();} return null ;}} /* // can be combined with the class automatic loading function class Factory {static function fruit ($ classname) {return new $ classname ();}}*/
// Test Factory: fruit ("Apple"); Factory: fruit ("Banana ");