設計模式是軟件工程基石。本文實現兩大創建型模式:
確保全局唯一實例,四要素:
newGetInstance() 獲取實例__clone() 防克隆class Singleton {
private static $_instance;
private function __construct() {}
private function __clone() {}
public static function GetInstance() {
if (!(self::$_instance instanceof self)) self::$_instance = new self();
return self::$_instance;
}
public function sayHi() { echo "Hi!"; }
}
Singleton::GetInstance()->sayHi();
集中實例化邏輯,配合接口實現多態:
interface ProductInterface { public function showInfo(); }
class ProductA implements ProductInterface { public function showInfo() { echo 'A'; } }
class ProductB implements ProductInterface { public function showInfo() { echo 'B'; } }
class Factory {
public static function create($type) {
$class = 'Product' . strtoupper($type);
if (class_exists($class)) return new $class();
throw new Exception("Invalid type");
}
}
Factory::create('A')->showInfo(); // A
單例保證唯一性,工廠解耦創建邏輯,配合接口實現「面向抽象編程」。