所有物件導向中最常見的三種設計模式分別是:工廠模式,單例模式,註冊(器)模式
工廠模式,工廠方法或類別產生對象,百不是在程式碼中直接new
單例模式,使某個類別的物件只允許建立一個
註冊模式,全域共用和交換物件
工廠模式factory.php
<?php class Database{ public function __construct() { return "Database\n"; } } //工厂类 class Factory{ public static function createDatabase() { $db = new Database(); return $db; } } $db = Factory::createDatabase(); $db1 = Factory::createDatabase(); $db2 = Factory::createDatabase(); var_dump($db, $db1, $db2); #object(Database)#1 (0) { #} #object(Database)#2 (0) { #} #object(Database)#3 (0) { #}
單例模式singleton.php
<?php //单例模式 class Database{ protected static $db; //构造方法私有,防止在外层直接new private function __construct(){ //code } static function getInstance(){ if (self::$db) { return self::$db; }else{ self::$db = new self(); return self::$db; } } } $db = Database::getInstance(); $db1 = Database::getInstance(); $db2 = Database::getInstance(); var_dump($db, $db1, $db2); #object(Database)#1 (0) { #} #object(Database)#1 (0) { #} #object(Database)#1 (0) { #}
工廠模式和單例結合使用
<?php class Database{ protected static $db; private function __construct(){ } static function getInstance(){ if (self::$db) { return self::$db; }else{ self::$db = new self(); return self::$db; } } } class Factory{ public static function createDatabase(){ return Database::getInstance(); } } var_dump(Factory::createDatabase());
註冊器類register.php
<?php //注册器模式 class Register { protected static $objects; static function set($alias, $object){ self::$objects[$alias] = $object; } static function get($name){ return self::$objects[$name]; } function _unset($alias){ unset(self::$objects[$alias]); } } Register::set('db1', $db); Register::get('db1');
更多PHP設計模式之工廠模式、單例模式和註冊模式相關文章請關注PHP中文網!