1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <?php use \Exception; class Singleton { /** * 对象实例 * @var object / public static $instance; /** * 获取实例化对象 / public static function getInstance() { if (!self::$instance instanceof self) { self::$instance = new self(); } return self::$instance; } /** * 禁止对象直接在外部实例 / private function __construct(){} /** * 防止克隆操作 / final public function __clone() { throw new Exception('Clone is not allowed !'); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | // SingletonFacotry.php <?php use \Exception; abstract class SingletonFacotry { /** * 对象实例数组 * @var array / protected static $instance = []; /** * 获取实例化对象 / public static function getInstance() { $callClass = static::getInstanceAccessor(); if (!array_key_exists($callClass, self::$instance)) { self::$instance[$callClass] = new $callClass(); } return self::$instance[$callClass]; } abstract protected static function getInstanceAccessor(); /** * 禁止对象直接在外部实例 / protected function __construct(){} /** * 防止克隆操作 / final public function __clone() { throw new Exception('Clone is not allowed !'); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // A.php <?php class A extends SingletonFactory { public $num = 0; protected static function getInstanceAccessor() { return A::class; } } $obj1 = A::getInstance(); $obj1->num++; var_dump($obj1->num); // 1 $obj2 = A::getInstance(); $obj2->num++; var_dump($obj2->num); // 2 |
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |