Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

php单利设计模式有哪些

作者:妳會吥會在吥經意間想起莪?   发布日期:2024-01-07   浏览:520

在PHP中,单例设计模式有以下几种实现方式:

  1. 饿汉式单例模式(Eager Initialization):在类加载时就创建实例对象,保证了线程安全,但可能会造成资源浪费。

    class Singleton {
     private static $instance = new Singleton();
    
     private function __construct() {}
    
     public static function getInstance() {
         return self::$instance;
     }
    }
  2. 懒汉式单例模式(Lazy Initialization):在第一次调用getInstance方法时才创建实例对象,避免了资源浪费,但可能会存在线程安全问题。

    class Singleton {
     private static $instance;
    
     private function __construct() {}
    
     public static function getInstance() {
         if (self::$instance == null) {
             self::$instance = new Singleton();
         }
         return self::$instance;
     }
    }
  3. 双重检查锁定单例模式(Double-Checked Locking):在懒汉式的基础上增加了同步锁,保证了线程安全和懒加载的特性。

    class Singleton {
     private static $instance;
    
     private function __construct() {}
    
     public static function getInstance() {
         if (self::$instance == null) {
             synchronized(self::class) {
                 if (self::$instance == null) {
                     self::$instance = new Singleton();
                 }
             }
         }
         return self::$instance;
     }
    }
  4. 静态内部类单例模式(Static Inner Class):利用PHP的命名空间特性,将实例对象封装在静态内部类中,保证了线程安全和懒加载的特性。

    class Singleton {
     private function __construct() {}
    
     public static function getInstance() {
         return SingletonHolder::$instance;
     }
    
     private static class SingletonHolder {
         private static $instance = new Singleton();
     }
    }

以上是常见的几种单例设计模式的实现方式,根据具体的需求和场景选择合适的方式。

上一篇:php批量添加栏目有哪些方法

下一篇:php的注释写法有哪些

大家都在看

php session用法

phpisset函数

php后端

php爬虫框架

php读取csv文件

php 三元表达式

php文件加密

php 拆分字符串

php pcntl

php ||

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站