zoukankan      html  css  js  c++  java
  • 单例

    单例类 如何设计  单例设计模式
    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;
       }

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

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

  • 相关阅读:
    hdu 6435 Problem J. CSGO 最长曼哈顿距离+二进制枚举
    UVA11419 SAM I AM 二分图最小点覆盖
    数论入门基础整理
    [算法导论]#1 摊还分析
    [转载]markown语法
    [AC自动机]玄武密码
    [学习笔记]AC自动机
    分火腿
    [学习笔记]二分与分治
    [学习笔记]二项式反演
  • 原文地址:https://www.cnblogs.com/wxlf/p/8117316.html
Copyright © 2011-2022 走看看