PHP Classic design mode-Simple Factory modepfinalIntroduced
We were going to get an instance of a class and need to use the New keyword. But if new is written directly into the business code, a class is instantiated in many places, and if there is something wrong with this class, such as changing a name (in practice, you may be more likely to modify the constructor method), then it is awkward and needs to be changed a lot.
Factory mode, as the name implies, is not to use new to obtain an instance, but to put the business class into a workshop class, by the factory (class) "Production" Out of the corresponding instance.
Realize
Simplefactory.PHP<?phpnamespace designpatterns\creational\simplefactory;classsimplefactory{ Public functionCreatebicycle ():Bicycle {return NewBicycle (); }}
Bicycle.PHP<?phpnamespace designpatterns\creational\simplefactory;classbicycle{ Public functionDriveto (string $destination) { }}
Use
$factory New $bicycle$factory,$bicycle->driveto (' Paris ');
What kind of examples do we need to get to the factory instance method. Only one instance of a class is defined here, and you can define more.
We see that the business code does not appear in the new and that specific business class, so that the business class (class Bicycle) We can arbitrarily change, in the future, as long as in the factory class (class Simplefactory) modified once, you can be a pair of more in the place to take effect.
However, the method name $factory->createbicycle (); You have to get good, if you want to change the name, or you have to change a number of places.
Summarize
The Rule factory class must have a factory method; The factory method must be able to return an instance of another class; only one instance can be created and returned at a time;
PHP Classic design mode-Simple Factory mode