PHP实现单件模式的几种方式

单件模式是我们在开发中经常用到的一种设计模式,利用PHP5面向对象的特性,我们可以很容易的构建单件模式的应用,下面是单件模式在PHP中的几种实现方法:

Php代码   收藏代码
  1. class Stat{  
  2.     static $instance = NULL;  
  3.      
  4.     static function getInstance(){  
  5.         if(self::$instance == NULL){  
  6.             self::$instance = new Stat();  
  7.         }  
  8.          
  9.         return self::$instance;  
  10.     }  
  11.      
  12.     private function __construct(){  
  13.     }  
  14.      
  15.     private function __clone(){  
  16.     }     
  17.      
  18.     function sayHi(){  
  19.         return "The Class is saying hi to u ";  
  20.     }  
  21. }  
  22.   
  23.   
  24. echo Stat::getInstance()->sayHi();  

 

这是一种最通常的方式,在一个getInstance方法中返回唯一的类实例。
对这里例子稍加修改,便可以产生一个通用的方法,只要叫道任何你想用到单件的类里,就可以了。

 

 

Php代码   收藏代码
  1. class Teacher{  
  2.     function sayHi(){  
  3.         return "The teacher smiling and said 'Hello '";  
  4.     }  
  5.      
  6.     static function getInstance(){  
  7.         static $instance;  
  8.          
  9.         if(!isset($instance)){  
  10.             $c = __CLASS__;  
  11.             $instance = new $c;  
  12.         }  
  13.          
  14.         return $instance;  
  15.     }  
  16. }  
  17.   
  18. echo Teacher::getInstance()->sayHi();  

 

最后一种是提供一个singleton类,然后通过调用getInstance方法,可以为任何一个类生产出一个实例来。

Php代码   收藏代码
  1. class singleton{  
  2.     function getInstance($class){  
  3.         static $instances = array();  
  4.         if(!array_key_exists($class,$instances)){  
  5.             $instances[$class] = &new $class;  
  6.         }  
  7.         $instance = $instances[$class];  
  8.          
  9.         return $instance;  
  10.     }  
  11. }  
  12.   
  13. class People{  
  14.     function sayHi(){  
  15.         return 'Hello i am a people?';  
  16.     }  
  17. }  
  18.   
  19. echo "<br />";  
  20. echo singleton::getInstance('People')->sayHi();  
 

通过这三种方法,我们可以很容易的应用单件模式,如果能够结合工厂模式,将使我们的编程变得更有条理和效率。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值