It is a headache for everyone to start with the model. The introduction and concepts of the big article also include class diagrams ..
A simple factory model does not belong to the 23rd model. Simple factories are generally divided into common simple factories, multi-method simple factories, and static method simple factories.
Simple factory mode:A dedicated class is defined to create instances of other classes. The created instance usually has a common parent class. It is also called the static factory method mode and belongs to the class creation mode.
The essence of the simple factory mode is that a factory class dynamically determines the product class to be created (these product classes inherit from a parent class or interface) based on the input parameters.
Simple Factory |
Simple multi-method Factory |
Simple static method Factory |
class SimpleFactory1{ public static function createService($name) { switch ($name) { case ‘value‘: return new Service1(); break; case ‘value‘: return new Service2(); break; default: break; } }} |
class SimpleFactory2{ public function createService1() { return new Service1() } public function createService2() { return new Service2() }} |
class SimpleFactory3{ public static function createService1() { return new Service1() } public static function createService2() { return new Service2() }} |
In the above three modes, if the input string is incorrect, the object cannot be correctly created, and the third mode does not need to instantiate the factory class. Therefore, in most cases, we will choose the third static factory method mode.
Second factory Model
Many people compare the factory model with the simple factory model. I still don't know why...
My understanding of the factory model is very simple. It is a class that implements Abstract Factory interfaces and is called by applications to create product objects. Let's look at an instance in zf2.
interface FactoryInterface{ public function createService(ServiceLocatorInterface $serviceLocator);}class EventManagerFactory implements FactoryInterface{ public function createService(ServiceLocatorInterface $serviceLocator) { $em = new EventManager(); $em->setSharedManager($serviceLocator->get(‘SharedEventManager‘)); return $em; }}
Creation Mode factory method mode, abstract factory mode, Singleton mode, builder mode, and prototype mode