Five common PHP design patterns-the factory model. Five common design patterns in PHP-the factory model has always had a sense of reverence for the design patterns. every time you want to see the design patterns, you will think of ErichGamma, Richard dhelm, five common design modes of ralkaline PHP-factory model
Always have a kind of reverence for the design pattern, every time you want to see the design pattern, you will thinkErich Gamma
,Richard Helm
,Ralph Johnson
,John Vlissides
Black skinDesign patterns
The book is not about to be read at half past one, and I feel like I am talking about it on paper without project experience.
TodayIBM Developerworks
See an article onPHP
The five common design patterns are good, and there are only five (three important times )! Let's start by simply eliminating these five types. Later, I will learn more about other design models.
Factory model (
Factory Pattern
)
The use of the word "factory" is very vivid. Literally, we can think that in this mode, we have a factory, this factory produces one or more products (in fact, many cases cover one), but we do not know how to produce and package each product, in fact, we do not need to know. the more you know, the more confused you will be. in the future, your behavior will be subject to too many chores, that is, we often say that the coupling is too high, therefore, we will give everything to the factory for responsibility. we only need to tell the factory what it needs, and the factory will deliver the product to you. Once the process of the product changes, the factory is responsible. the process of using the product is not affected. Therefore, the factory mode can greatly reduce the coupling degree of the system and enhance the stability of the system. of course, it will also increase the code reuse rate.
In actual programming, the factory is equivalent to an external interface, so the return type of this interface is determined. how can we use this factory to produce different products and send them back to customers? It is easy to create a "model" for all products. this "model" has all the features of each product, but it is not usable. a specific product is required to implement these features, this is what we often callInterface
.
The class diagram is shown as follows:
PHP
To compile an interface
Product.php
Design a productA
ImplementationProduct
Interface
Design ProductB
ImplementationProduct
Interface
Build a factory to produce productsA
AndB
Test
ProductA
AndB
The factory has been designed, and the next step is to test the production capacity of the factory.
factory('ProductA')->getName().PHP_EOL;echo $factory->factory('ProductB')->getName();
The output result is as follows:
Everyone has always been in awe of the design patterns. every time you want to see the design patterns, you will think of Erich Gamma, Richard Helm, ralkaline...