版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wide288/article/details/85165055
1,单例模式,138页
问题:一个对象应该可以被系统中的任何对象使用。
这个对象不应该被储存在会被覆写的全局变量中。
系统中不应超过一个这个对象。生成一个且只生成一个对象实例的特殊类。
实现,139页
class Preferences {
private $props = array();
private static $instance;
private function __construct() { }
public static function getInstance() {
if ( empty( self::$instance ) ) {
self::$instance = new Preferences();
}
return self::$instance;
}
public function setProperty( $key, $val ) {
$this->props[$key] = $val;
}
public function getProperty( $key ) {
return $this->props[$key];
}
}
单例模式的使用:
$pref = Preferences::getInstance();
$pref->setProperty( “name”, “matt” );