php设计模式 Factory(工厂模式)
程序员文章站
2022-08-03 21:22:51
复制代码 代码如下:
<?php
/**
* 工厂方法模式
*
* 定义一个用于创建对象的接口,让子类决定将哪一个类实例化,使用一个类的实例化延迟到其子类
*/
/*
class dbfactory
{
public static function create($type)
{
swtich($type)
{
case "mysql":
return new mysqldb(); break;
case "postgre":
return new postgredb(); break;
case "mssql":
return new mssqldb(); break;
}
}
}
*/
class dbfactory
{
public static function create($type)
{
$class = $type."db";
return new $class;
}
}
interface db
{
public function connect();
public function exec();
}
class mysqldb implements db
{
public function __construct() {
echo "mysql db<br/>";
}
public function connect() {
}
public function exec() {
}
}
class postgredb implements db
{
public function __construct() {
echo "postgre db<br/>";
}
public function connect() {
}
public function exec() {
}
}
class mssqldb implements db
{
public function __construct() {
echo "mssql db<br/>";
}
public function connect() {
}
public function exec() {
}
}
$omysql = dbfactory::create("mysql");
$opostgre = dbfactory::create("postgre");
$omssql = dbfactory::create("mssql");
复制代码 代码如下:
<?php
/**
* 工厂方法模式
*
* 定义一个用于创建对象的接口,让子类决定将哪一个类实例化,使用一个类的实例化延迟到其子类
*/
/*
class dbfactory
{
public static function create($type)
{
swtich($type)
{
case "mysql":
return new mysqldb(); break;
case "postgre":
return new postgredb(); break;
case "mssql":
return new mssqldb(); break;
}
}
}
*/
class dbfactory
{
public static function create($type)
{
$class = $type."db";
return new $class;
}
}
interface db
{
public function connect();
public function exec();
}
class mysqldb implements db
{
public function __construct() {
echo "mysql db<br/>";
}
public function connect() {
}
public function exec() {
}
}
class postgredb implements db
{
public function __construct() {
echo "postgre db<br/>";
}
public function connect() {
}
public function exec() {
}
}
class mssqldb implements db
{
public function __construct() {
echo "mssql db<br/>";
}
public function connect() {
}
public function exec() {
}
}
$omysql = dbfactory::create("mysql");
$opostgre = dbfactory::create("postgre");
$omssql = dbfactory::create("mssql");
上一篇: 吃猪腰有什么营养,怎么吃猪腰最好
下一篇: php函数的常用方法及注意之处小结