单模式的定义:确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
优点
使用场景
单模式的如下面代码所示。
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| <?php
class Singleton {
private static $_instance = NULL;
private function __construct() { }
public static function getInstance() { if (is_null(self::$_instance)) { self::$_instance = new Singleton(); } return self::$_instance; }
public function __clone(){ die('Clone is not allowed.' . E_USER_ERROR); }
public function test() { echo 'Singleton Test!'; } }
class Client {
public static function main() { $instance = Singleton::getInstance(); $instance->test(); } } Client::main(); ?>
|