php工厂模式
工厂模式:工厂类调用自身方法来生产对象实例。
示例:
interface DbFactory{ public function new_db(); } interface DbCls{ public function connect_db(); public function query(); //... } //mysql数据库 class factory_mysql implements DbFactory{ public function new_db(){ return new db_mysql(); } } class db_mysql implements DbCls{ public function connect_db(){ echo 'mysql connect'; } public function query(){ echo 'mysql query'; } } //sqlite数据库 class factory_sqlite implements DbFactory{ public function new_db(){ return new db_sqlite(); } } class db_sqlite implements DbCls{ public function connect_db(){ echo 'db_sqlite connect'; } public function query(){ echo 'db_sqlite query'; } } //调用mysql $obj = new factory_mysql(); $db = $obj->new_db(); $db->connect_db(); $db->query(); //调用sqlite $obj = new factory_sqlite(); $db = $obj->new_db(); $db->connect_db(); $db->query(); //如果新增加一个数据库类 //只需要添加新的类,不用修改原有的类 //sqlite数据库 class factory_oracle implements DbFactory{ public function new_db(){ return new db_oracle(); } } class db_oracle implements DbCls{ public function connect_db(){ echo 'db_oracle connect'; } public function query(){ echo 'db_oracle query'; } } $obj = new factory_oracle(); $db = $obj->new_db(); $db->connect_db(); $db->query();