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也就不存在这个问题了。

  • 相关阅读:
    QString乱谈(2)
    QString 乱谈(1)
    Mingw版QtCreator调用VS编译的C++库的方法
    webrtc doubango linphone
    Neo4j图数据库配置文件详解
    Spring系列之Spring常用注解总结
    写一手好SQL很有必要
    史上最全的MySQL高性能优化实战总结!
    elasticsearch 亿级数据检索案例与原理
    Rust 优劣势: v.s. C++ / v.s. Go(持续更新)
  • 原文地址:https://www.cnblogs.com/jesseZh/p/3051422.html
Copyright © 2011-2022 走看看