[php]单例模式又叫单件模式面向对象设计
2012/10/11 23:02:00 人气 3311 编程语言区<?php
header(‘content-Type:text/html;charset=utf-8‘);
class preferences{
private $$store = array(‘九‘,‘八‘,‘七‘);
static private $$obj = null;
//构造函数设置为私有的,那么类外就不能直接调用了,也就保障了不能在类外通过new爱执行实例化了
//public function __construct(){}
private function __construct(){
}
static public function getInstance(){
if(empty(self::$$obj)){
$$obj = new preferences();
//$$this->obj =$$obj;
self::$$obj = $$obj;
}
return self::$$obj;
}
public function show(){
echo ‘<pre>‘;
var_dump($$this->store);
}
public function add($$var){
array_push($$this->store,$$var);
}
}
//$$obj1 = new preferences();
$$obj1 = preferences::getInstance();
$$var = ‘二十二‘;
$$obj1->add($$var);
$$obj1->show();
echo ‘----------------------<br />‘;
//$$obj2 = new preferences();
$$obj2 =preferences::getInstance();
$$obj2 ->show();
$$obj3 = preferences::getInstance();
$$var = ‘二十‘;
$$obj3->add($$var);
$$obj3->show();
echo ‘----------------------<br />‘;
//$$obj2 = new preferences();
$$obj4 =preferences::getInstance();
$$obj4 ->show();
header(‘content-Type:text/html;charset=utf-8‘);
class preferences{
private $$store = array(‘九‘,‘八‘,‘七‘);
static private $$obj = null;
//构造函数设置为私有的,那么类外就不能直接调用了,也就保障了不能在类外通过new爱执行实例化了
//public function __construct(){}
private function __construct(){
}
static public function getInstance(){
if(empty(self::$$obj)){
$$obj = new preferences();
//$$this->obj =$$obj;
self::$$obj = $$obj;
}
return self::$$obj;
}
public function show(){
echo ‘<pre>‘;
var_dump($$this->store);
}
public function add($$var){
array_push($$this->store,$$var);
}
}
//$$obj1 = new preferences();
$$obj1 = preferences::getInstance();
$$var = ‘二十二‘;
$$obj1->add($$var);
$$obj1->show();
echo ‘----------------------<br />‘;
//$$obj2 = new preferences();
$$obj2 =preferences::getInstance();
$$obj2 ->show();
$$obj3 = preferences::getInstance();
$$var = ‘二十‘;
$$obj3->add($$var);
$$obj3->show();
echo ‘----------------------<br />‘;
//$$obj2 = new preferences();
$$obj4 =preferences::getInstance();
$$obj4 ->show();
自从来到了琴剑听月,忽然找到了生活最大的乐趣!琴剑听月!我的最爱!
暂无回复!
发表回复