PHP中的单件模式

<? php


    
require_once   ' DB.php '
;
    
    
class
 DatabaseConnection{
        
public   static   function
 get(){
            
static   $db   =   null
;
            
if ( $db   ===   null
){
                
$db   =   new
 DatabaseConnection();
            }
            
return   $db
;
        }
        
        
private   $_handle   =   null
;
        
        
#  构造方法是私有的,所以不能字节使用 new 关键字实例化,这点对于单件模式至关重要

         private   function  __construct(){
            
$dsn   =   ' mysql://root:root@localhost/test '
;
            
$this -> _handle  =  DB :: connect( $dsn ,   array
());
        }
        
        
public   function
 handle(){
            
return   $this ->
_handle;
        }
    }
    
print " Handle =  " . DatabaseConnection :: get() -> handle() . " "
 );
    
print " Handle =  " . DatabaseConnection :: get() -> handle() . " "
 );
    
    
print_r ( get_included_files
());



    
#  下面是单件模式的原型,注意三个要点,

         #  1. 对象必须是私有成员.
         #  2.私有的构造函数
         #  3. 一个公共的实例化并返回该Singleton的可被外部对象调用的成员函数
     #  单件模式的事例化过程被从外部移到了内部.只有通过内部方法才能实例化对象
     class  Singleton{
        
private   static   $instance   =   null
;
    
        
private   function
 __construct(){
        }
        
        
public   static   function
 getInstance(){
        
            
if (self :: $instance   ===   null
){
                self
:: $instance   =   new
 Singleton();
            }
            
return  self ::
instance;
        }
    }

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值