zoukankan      html  css  js  c++  java
  • 单例设计模式

    单例模式可以分为两种: 1. 饿汉模式  2. 懒汉模式

    饿汉模式:PHP不支持(以下是java代码)

      public class Singleton{
                private static Singleton singleton = new Singleton ();
                private Singleton (){}
                public Singleton getInstance(){return singletion;}
      }

    懒汉模式:

    <?php
    class LazySingleton {
        private static $_instance = null;

        private function __construct() {}
           
        public static function getInstance() {
            if(!isset(self::$_instance)) {
                # self::$_instance = new __CLASS__;  
                self::$_instance = new LazySingleton();   
            }
            return self::$_instance;   
        }

        public function operation() {
            echo 'lazy singleton <br>';
        }

        //防止克隆
        public function __clone() {
            trigger_error('Clone is not allow.', E_USER_ERROR);
        }   
    }

    $singleton = LazySingleton::getInstance();
    $singleton->operation();
    ?>

    容易出错的地方: HungerSingleton 不支持饿汉模式,由于PHP中属性只支持 常量初始化,new HungerSingleton() 会出现 T_NEW类型的错误。

    self::$_instance = new __CLASS__;  __CLASS__ 不能直接这么new  如果需要可以才用  $c =  __CLASS__; self::$_instance = new $c; 的形式。

    关于线程安全的问题。由于PHP自身不存在多线程,所有采用lazy singleton也就不存在这个问题了。

  • 相关阅读:
    x32dbg之AttachHelper插件
    x32dbg插件之APIInfo
    x32dbg之Scylla脱壳插件
    x32dbg插件之strongOD(又名SharpOD)
    x32dbg新型插件之loli(萝莉)
    7 个超棒的监控工具
    成为程序员前需要做的10件事
    改良程序的11个技巧
    旧衣物捐献地址和注意事项
    一件衣服好不好,看看标签就知道
  • 原文地址:https://www.cnblogs.com/jesseZh/p/3051422.html
Copyright © 2011-2022 走看看