PHP design pattern series-factory pattern

Source: Internet
Author: User
The factory mode provides an interface for obtaining an object instance, and allows you to call the code to avoid the steps to determine whether to instantiate the base class. The factory mode is actually to create a unified class instantiation function interface. Unified invocation and control. The factory mode is the most common design mode in php project development,... SyntaxHighlighter. all ();

Factory model
Provides an interface for obtaining an object instance, and allows you to call code to avoid the steps to determine whether to instantiate the base class.
The factory mode is actually to create a unified class instantiation function interface. Unified invocation and control.
The factory mode is the most common design mode in php project development. it is usually used together with the singleton mode to load classes in the php class library.
Application scenarios
We have a Json, String, and Xml class.
If we do not use the factory method to instantiate these classes, we need to create a new class. The process is uncontrollable and there are more classes. new classes are everywhere.
Introduce the factory mode to create a unified object instance through the factory.
Code:
[Php] www.2cto.com
// The Factory mode provides an interface for obtaining an object instance, and calls the code to avoid the steps to determine the instantiation of 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 type
Class Factory {
Public static function create ($ class ){
Return new $ class;
}
}
Factory: create ("Json"); // Obtain the Json object

 

Author: initphp

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.