PHP設計模式------單例模式
阿新 • • 發佈:2017-12-31
生命 靜態綁定 技術分享 ted xiaomi function 繼承 運行 col
單例模式的作用就是在整個應用程序的生命周期中,單例類的實例都只存在一個,同時這個類還必須提供一個訪問該類的全局訪問點。
首先創建一個單例類,可以直接使用這個單例類獲得唯一的實例對象,也可以繼承該類,使用子類實例化對象。
下面的代碼使用子類進行實例對象創建
Singleton.php文件
<?php namespace test; class Singleton { protected static $instance; private function __construct() { } /* static 的用法是後期靜態綁定:根據具體的上下文環境,確定使用哪個類*/ public static function getInstance() { /* $instance 如果為NULL,新建實例對象 */ if (NULL === static::$instance) { echo ‘before‘ . PHP_EOL; static::$instance = new static(); echo ‘after‘ . PHP_EOL; } /* 不為NULL時,則直接返回已有的實例*/ return static::$instance; } }
SingletonTest.php子類文件
<?php namespace test; require_once(‘Singleton.php‘); class SingletonTest extends Singleton { private $name; public function __construct() { echo ‘Create SingletonTest instance‘ . PHP_EOL; } publicfunction setName($name) { $this->name = $name; } public function getName() { echo $this->name . PHP_EOL; } } /* SingletonTest instance */ $test_one = SingletonTest::getInstance(); $test_one->setName(‘XiaoMing‘); $test_one->getName(); /* $test_two 和 $test_one 獲取的是同一個實例對象 */ $test_two = SingletonTest::getInstance(); $test_two->getName();
命令行下運行結果:
PHP設計模式------單例模式