Five common design patterns in PHP-the factory model has always been in awe of the design patterns, and every time you want to see the design patterns, you will think of Erich Gamma, Richard Helm, Ralph Johnson, john Vlissides's "design pattern" is basically a hope and a stop. it is not a half past one meeting to finish the book. In addition, without project experience, I feel like I am talking about it on paper.
Today, I saw an article on IBM Developerworks describing the five common design patterns in PHP. I feel pretty good, and there are only five of them (three important times )! Let's start by simply eliminating these five types. Later, I will learn more about other design models.
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 call interfaces.
The class diagram is shown as follows:
PHP implementation
Compile an interface Product. php
Design A Product A to implement the Product interface
Design Product B to implement the Product interface
Build A factory to produce products A and B TestProduct A and product B have been designed and the factory has been built. 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:
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.