Home  >  Article  >  Backend Development  >  PHP Design Pattern Series - Factory Pattern_PHP Tutorial

PHP Design Pattern Series - Factory Pattern_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 17:52:08910browse

Factory Mode
Provides an interface for obtaining an instance of an object while enabling the calling code to avoid determining the steps to instantiate a base class.
Factory pattern is actually to establish a unified functional interface for class instantiation. Unified call, unified control.
The factory pattern is the most commonly used design pattern in PHP project development. It is generally used in conjunction with the singleton pattern to load classes in the PHP class library.
Application scenarios
We have a Json class, String class, and Xml class.
If we don’t use the factory method to instantiate these classes, each class needs to be new. The process is uncontrollable. There are too many classes, and new is everywhere
Introduce the factory pattern and create object instances uniformly through the factory.
Code:
[php] www.2cto.com
//Factory pattern provides an interface for obtaining an instance of an object, while allowing the calling code to avoid determining the steps to instantiate the base class
//String class
class String {
Public function write() {}
}
//Json class
class Json {
Public function getJsonData() {}
}
//xml class
class Xml {
Public function buildXml() {}
}
//Factory class
class Factory {
Public static function create($class) {
          return new $class;
}  
}
Factory::create("Json"); //Get Json object

Author: initphp

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478147.htmlTechArticleThe factory pattern provides an interface for obtaining an instance of an object, while allowing the calling code to avoid determining the steps to instantiate the base class. . Factory pattern is actually to establish a unified class instantiation...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn