Learn Design Patterns with me (ii), learn to design patterns
Factory mode is very important in the design of polymorphism, and if applied properly, it can make the application more portable and the dependencies between classes more loosely, thus increasing flexibility. If the singleton mode is the responsibility of the class, then the factory pattern is the polymorphism of the class.
So what is a factory class?
Concept: A factory class is a class that contains a method that is designed to create other objects.
Scenario: Factory mode is typically used to return different classes that conform to similar interfaces. That is, the factory class can allow us to decide which class to instantiate based on the logic of the configuration or application.
The following is a simple factory class code:
Interfaceidatabase {//... Public functionQuery$sql);}classDbfactory { Public Static functionCreate$type){ $db=NULL; Switch($type) { Case' MySQL ':$db=New Mysql(/**arguments*/); Break; Case' SQLite ':$db=NewSqlite (/**arguments*/); Break; Case' Pgsql ':$db=NewPgsql (/**arguments*/); Break; default:#code ... Break; } return $db; }}class Mysql ImplementsIdatabase {//... Public functionQuery$sql){ }}/**other class ...*/
Use factory class:
$db = dbfactory::create (' mysql '); $db->query (' Show database ');
Each of our databases inherits the specified interface, which is done to make all database objects behave consistently externally. External classes can be assured of the use of the interface declaration method, that is, our software engineering is often said to the user transparent. If one day, because the engine room changes, we want to switch to another database, we just follow the interface to implement the relevant database classes, business code does not need to change. This reflects the flexibility and polymorphism of the factory class.
From another point of view, we are concentrating the changes on the entrance. There is no need for if-else repetitive processing of these changes internally.
Well, the theory of the content of only so much, more experience needs to be used in the project, more experience its benefits.
http://www.bkjia.com/PHPjc/918064.html www.bkjia.com true http://www.bkjia.com/PHPjc/918064.html techarticle Learn the design pattern with Me (ii), learning to design patterns is very important in the design of polymorphism, if applied properly, can make the application more portable, between the class ...