Questions about the factory model

Source: Internet
Author: User
Example #1 call the Factory method (with parameters) & lt ;? PhpclassExample {& nbsp; // Theparameterizedfactorymethod & nbsp; publicstaticfunctionfactory ($ type) & nbs about factory mode
Example #1 call the Factory method (with parameters)
Class Example
{
// The parameterized factory method
Public static function factory ($ type)
{
If (include_once 'Drivers/'. $ type.'. php '){
$ Classname = 'driver _ '. $ type;
Return new $ classname;
} Else {
Throw new Exception ('Driver not found ');
}
}
}
?>
Drivers can be dynamically loaded in the above method. If the Example class is a database abstract class, you can generate the MySQL and SQLite driver objects as follows:
// Load a MySQL Driver
$ Mysql = Example: factory ('mysql ');

// Load a SQLite Driver
$ Sqlite = Example: factory ('sqlite ');
?>


Original article address:
Http://www.php.net/manual/zh/language.oop5.patterns.php


I want to know what the role of this model is.

In addition, the class name containing the file must be prefixed with "Driver _". isn't it inconvenient and restrictive?

In this way, what dynamics have we achieved?

------ Solution --------------------
Driver_MySQL and Driver_SQLite implement the same interface, so your program does not have to worry about which database is used, so that you can change the database system in the future (of course, there may still be problems with SQL statements)
As to why the Driver _ prefix is, it is worried that duplicate class names may occur, or it is set for convenience of management.
------ Solution --------------------
What is the role of this mode...
The abstraction is higher than the implementation. The Factory mode uses a specific class when creating an object of the abstract type.

Driver, do you think that adding a prefix is very eye-catching, or do you think $ a, $ B, and $ c can help you understand what it is? You can't even guess. no...

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.