實現一個類只能被例項化一次
阿新 • • 發佈:2019-02-06
單例模式:達到只有一個例項
程式碼如下:
<?php class C{ private static $_instance; private function __construct(){ } public static function getInstance(){ if(!(self::$_instance instanceof self)){ self::$_instance = new self; } return self::$_instance; } } $o = C::getInstance(); ?>
工廠模式:專門用於生產物件
程式碼如下:
<?php class C { } class Factory { private static $instances;//儲存所有的例項 public static function getInstance($class_name) { $class_name = strtolower($class_name);//將所有的都轉換成小寫 if(!isset(self::$instances[$class_name])) { self::$instances[$class_name] = new $class_name; } return self::$instances[$class_name]; } } $c1 = Factory::getInstance('C'); ?>