php设计模式之单例模式
2017-03-15 10:20
302 查看
<?php /** * @desc 单例模式 * 目的:防止过多的new对象和clone对象,没有对象的时候new对象并缓存,始终保持都是同一个对象实例 * 特点:php的单例是进程中的单例,而不像java属于内存中的单例 * **/ class single{ protected static $ins = null;//声明一个静态变量,用来存储类的实例 private $name;//声明一个私有的实例变量 /** * 私有化构造方法,防止不断的创建对象 * **/ private function __construct(){ } public static function getIns(){ if(self::$ins===null){ self::$ins = new self(); } return self::$ins; } public function setName($name){ $this->name = $name; } public function getName(){ return $this->name; } } $single1 = single::getIns(); $single2 = single::getIns(); $single1->setName('hello world!'); $single2->setName('hello php!'); echo $single1->getName();//输出结果:hello php! echo $single2->getName();//输出结果:hello php! /*** * 分析:输出的结果都是hello php! * 采用了单例模式对象$single1与$single2是等价的,因此对象$single1与$single2都在设置类的变量时指向都是一致的,变量值取对象设置的最新的一个值 * **/
相关文章推荐
- 一种PHP设计模式:DPT
- 架构师常用的五种 PHP 设计模式
- [介绍]PHP设计模式:DAO(数据访问对象模式)
- 五种常见的 PHP 设计模式
- php设计模式介绍之值对象模式第1/5页
- 一种PHP设计模式:DPT
- 介绍php设计模式中的工厂模式
- 一种PHP设计模式:DPT
- 一种PHP设计模式:DPT
- [PHP设计模式]Composite(组合)模式范例
- [转]五种常见的PHP设计模式
- 五种常见的PHP设计模式
- 五种常见的PHP设计模式(择自互联网非本人所写)
- [转]五种常见的PHP设计模式
- 五种常见的 PHP 设计模式
- [介绍]PHP设计模式:DAO(数据访问对象模式)
- 五种常见的PHP设计模式
- php设计模式-中级
- php设计模式介绍之编程惯用法第1/3页
- 介绍php设计模式中的工厂模式