工厂方法


class IndexController extends Controller
{
    //抽象工厂方法
    public function test()
    {
        $mysql  = Mysql::getInstance();
        $mysqli = Mysqli::getInstance();
        $pdo    = Pdo::getInstance();
    }

}
interface Factory
{
    //获取实例
    public static function getInstance();

}
//mysql
class Mysql implements Factory
{

    public static function getInstance()
    {
        // TODO: Implement getInstance() method.
        return mysql_connect('127.0.0.1', 'root', '123456');
    }

}
//mysqli
class Mysqli implements Factory
{
    public static function getInstance()
    {
        // TODO: Implement getInstance() method.
        return mysqli_connect('127.0.0.1', 'root', '123456', 'testDb');
    }
}
//pdo
class Pdo implements Factory
{
    public static function getInstance()
    {
        // TODO: Implement getInstance() method.
        return new PDO('mysql:host=127.0.0.1;dbname=test', 'root', 'password');
    }
}

你可能感兴趣的:(工厂方法)