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

    单例模式是一种比较常用的设计模式,在很多框架中可以看到它的身影。通过单例模式可以确保类只有一个实例化,从而方便对实例个数的控制并节约系统资源。

    
    <?php
    
    use Exception;
    
    class Singleton
    {
        /**
         * 对象实例
         * @var object
         /
        public static $instance;
        
        /**
         * 获取实例化对象
         /
        public static function getInstance()
        {
            if (!self::$instance instanceof self) {
                self::$instance = new self();
            }
            
            return self::$instance;
        }
        
        /**
         * 禁止对象直接在外部实例
         /
        private function __construct(){}
        
        /**
         * 防止克隆操作
         /
        final public function __clone()
        {
            throw new Exception('Clone is not allowed !');
        }
    }
    

    一个系统中可能会多次使用到单例模式,为了更加方便的创建,可以试着建立一个通用的抽象:

    
    // SingletonFacotry.php
    <?php
    
    use Exception;
    
    abstract class SingletonFacotry
    {
        /**
         * 对象实例数组
         * @var array
         /
        protected static $instance = [];
        
        /**
         * 获取实例化对象
         /
        public static function getInstance()
        {
            $callClass = static::getInstanceAccessor();
            if (!array_key_exists($callClass, self::$instance)) {
                self::$instance[$callClass] = new $callClass();
            }
            
            return self::$instance[$callClass];
        }
        
        abstract protected static function getInstanceAccessor();
        
        /**
         * 禁止对象直接在外部实例
         /
        protected function __construct(){}   
        
        /**
         * 防止克隆操作
         /
        final public function __clone()
        {
             throw new Exception('Clone is not allowed !');
        }
    }
    
    
    // A.php 
    <?php
    
    class A extends SingletonFactory
    {
        public $num = 0;
    
        protected static function getInstanceAccessor()
        {
            return A::class;
        }
    }
    
    $obj1 = A::getInstance();
    $obj1->num++;
    var_dump($obj1->num); // 1
    $obj2 = A::getInstance();
    $obj2->num++;
    var_dump($obj2->num); // 2
    
    

    原文地址:https://segmentfault.com/a/1190000016777913

  • 相关阅读:
    Java基础
    第11章 处理概括关系
    第10章 简化函数调用
    第9章 简化条件表达式
    第8章 重新组织数据(暂略)
    第7章 在对象之间搬移特性
    第6章 重新组织函数
    【剑指offer】57
    【每日一题-leetcode】45.跳跃游戏 ||
    【左神算法】随机+荷兰国旗优化版快排
  • 原文地址:https://www.cnblogs.com/lalalagq/p/9964355.html
Copyright © 2011-2022 走看看