The content of this article is about the simple factory of PHP design pattern. It has certain reference value. Now I share it with you. Friends in need can refer to it.
Design pattern is a must for advanced architects. A knowledge system that needs to be understood. As a beginner, I actually already understood some concepts of design patterns when I took the architect exam in 2017. However, due to lack of experience, I could not combine it well with the code, so I used the combination at the beginning of 2018 Take a good look at the code.
Personally, I feel that after reading a lot of information on the Internet, I am also grateful to the many sharers on the Internet. When learning design patterns, you must understand the logic clearly and then make your own decisions in your mind. Think about it, then create your own scene and try to code it again.
The following is a record of some of my own experiences (focuses on understanding the ideas, may not be written in compliance with the standards):
Does not belong to the 23 design patterns Simple Factory (Simple Factory) pattern:
<?php // 简单工厂方法 index.php客户端 header("Content-Type:text/html;charset=utf-8"); require_once "SimpleFactory.php"; $hero = "关羽"; // $hero = "张飞"; // 实例化 $ob = SimpleFactory::Display($hero); // ::调用静态方法 $ob -> Create();
<?php /** Hero * 英雄接口 */ interface Hero { function Create(); } /** GuanYu * 关羽英雄类 */ Class GuanYu implements Hero { function Create() { echo "关羽加入战场。。。<br/>"; } } /** ZhangFei * 张飞英雄类 */ Class ZhangFei implements Hero { function Create() { echo "张飞加入战场。。。<br/>"; } } /** SimpleFactory * 简单工厂类 统一创建方法 与客户端交互 */ Class SimpleFactory{ static function Display($hero) { if($hero == "关羽") { return new GuanYu(); } else if($hero == "张飞") { return new ZhangFei(); } else { echo "英雄不存在"; } } }
Related recommendations:
State pattern definition of PHP design pattern and usage
The above is the detailed content of PHP design pattern simple factory. For more information, please follow other related articles on the PHP Chinese website!