单例

单例类 如何设计  单例设计模式
class Student
{

}

$s1 = new Stuent();//凡是new 都会在堆内存开辟空间
$s2 = new Stuent();

print($s1 == $s2);//false

class SingleTon
{
   //3 将内部产生的唯一实例缓存起来
   private static $instance;
   //private static $instance = new SingleTon();

   //1 构造器私有化
   private __construct function()
   {

   }

   //2 必须提供一个公开访问的方法 获取唯一实例
   public static getInstance()
   {
      if($instance == null)
      {
         $instance = new SingleTon();
      }
      return $instance;
   }

   private __clone{}
}

$s3 = SingleTon::getInstance();
$s4 = SingleTon::getInstance();

3个补充
   1.分为懒汉式和饿汉式

   2.注意__clone

   3.在多线程环境下,多个请求并发访问同一段代码时候如何保证单例 ,加锁的机制,可能导致线程问题的代码锁起来
  
     public static getInstance()
   {
      //同步代码块 加锁
      synchronous
      {
         if($instance == null)
         {
             $instance = new SingleTon();
         }
 
      }
      return $instance;
   }

 扩展:加锁的范围有讲究:锁的越多,效率越低
      可以锁代码块,可以锁代码块所在的方法,可以锁代码块所在方法所在对象

      对比 数据库有行级锁、列级锁,表级别锁!!!

posted @ 2017-12-26 11:56  wxlf  阅读(126)  评论(0编辑  收藏  举报