笔记3:工厂模式

对修改封闭,对扩展开放


// 共同接口
interface db
{
    function conn();
}

class dbmysql implements db
{
    public function conn()
    {
        echo '连接上了MySQL';
    }
}

class dbsqlite implements db
{
    public function conn()
    {
        echo '连接上了sqlite';
    }
}

interface Factory
{
    public function createDB();
}

class MySqlFactory implements Factory
{

    public function createDB()
    {
        return new  dbmysql();
    }
}

class SqliteFactory implements Factory
{

    public function createDB()
    {
        return new dbsqlite();
    }
}

$fact = new MySqlFactory();
$db = $fact->createDB();
$db->conn();

$fact = new SqliteFactory();
$db = $fact->createDB();
$db->conn();


// 扩展oracle 
class dboracle implements db
{
    public function conn()
    {
        echo '连接上了oracle';
    }
}

class OracleFactory implements Factory
{

    public function createDB()
    {
        return new dboracle();
    }
}

$fact = new OracleFactory();
$db = $fact->createDB();
$db->conn();