设计模式1(简单工厂模式,策略模式)
<?php /** 简单工厂模式 **/ abstract class CDb { abstract function connect(); abstract function query(); } class CMysqlDB extends CDb { function connect() { echo 'mysql connect success'; } function query() { echo 'mysql query'; } } class CMssqlDb extends CDb { function connect() { echo 'mssql connect success'; } function query() { echo 'mssql query'; } } class DbManager { static function createDataBase($type) { $db = null; switch($type) { case 'mysql': $db = new CMysqlDB(); break; case 'mssql': $db = new CMssqlDb(); break; } return $db; } } $type = 'mysql'; $db = DbManager::createDataBase($type); $db->connect(); $db->query(); <?php /** 策略模式 **/ abstract class CDb { abstract function connect(); abstract function query(); } class CMysqlDB extends CDb { function connect() { echo 'mysql connect success'; } function query() { echo 'mysql query'; } } class CMssqlDb extends CDb { function connect() { echo 'mssql connect success'; } function query() { echo 'mssql query'; } } class DbManager { private $db; function createDataBase($type) { switch($type) { case 'mysql': $this->db = new CMysqlDB(); break; case 'mssql': $this->db = new CMssqlDb(); break; } } function getDb() { return $this->db; } } $dbmanager = new DbManager(); $dbmanager->createDataBase('mysql'); $dbmanager->getDb()->connect();