PHP - 工厂模式

<?php

interface db{

  function  conn();

}

interface Factory{

  function  createDB();

}

class dbmysql implements db{

  public function conn(){

    echo '';

  }

}

class dbsqlite implements db{

  public function conn(){

    echo '';

  }

}

 

class mysqlFactory implements Factory{

  public function createDB(){

    return new dbmysql();

  }

 

}

 

class sqliteFactory implements Factory{

  public function createDB(){

 

    return new dbsqlite();

 

  }

 

}

// 工厂模式 ---- 例如多个类型数据库或者不同支付的时候用

class Factory{

  public static function createDB($type){

    if($type == 'mysql'){

      return new dbmysql();

    }else if($type == 'sqlite'){

      return new dbsqlite();

    }

  }

}

$mysql = Factory::createDB('mysql');

$mysql -> conn();

//方式 2

 

$mysql = new -> mysqlFactory();

 

$db = $mysql->createDB();

$db -> conn();

 

?>

posted @ 2021-11-16 16:33  让双脚&去腾空  阅读(24)  评论(0编辑  收藏  举报