PHP语言设计模式之单例模式

第1关:饿汉式

<?php
    class Singleton
    {
        public $name;
        /********** Begin **********/
        /********** 1. 单例模式的类只能有一个实例,并由类自己创建(此处略) **********/
        public static $instance;

        /********** 2. 构造函数必须为私有 **********/

        private function __construct(){
    }

        /********** 3. 克隆函数必须为私有 **********/
        private function __clone(){
       
        }
        /********** 4. 必须提供一个静态的访问方法 **********/
        public static function getInstance()
        {
            if(!(self::$instance instanceof self)){
                self::$instance = new self();
            }
            return self::$instance;
        }
        /********** End **********/
    }

第2关:懒汉式

<?php
    class Singleton
    {
        public $name;
        /********** Begin **********/
        /********** 1. 单例模式的类只能有一个实例 **********/
        private static $instance;

        /********** 2. 构造函数必须为私有 **********/
        private function __construct()
        {
        }
        /********** 3. 克隆函数必须为私有 **********/
        private function __clone()
        {
        }
        /********** 4. 必须提供一个静态的访问方法,并在每次调用时判断实例是否存在 **********/
        public static function getInstance()
        {
            if (!(self::$instance instanceof self)){
                self::$instance = new self();
            }
            return self::$instance;
        }
        /********** End **********/
    }

第3关:封装-通用单例基类

<?php
    abstract class Singleton
    {
        public $name;
        /********** Begin **********/
        /********** 1. 单例模式的类只能有一个实例 **********/
        protected static $instance;

        /********** 2. 构造函数必须为私有 **********/
        private function __construct()
        {
        }
        /********** 3. 克隆函数需要为protected,会被子类继承但不允许子类重写 **********/
        protected function __clone() 
        {
        }
        /********** 4. 必须提供一个静态的访问方法,并在每次调用时判断实例是否存在,且不允许子类重写 **********/
        public final function getInstance()
        {
            if (!self::$instance instanceof self) {
                self::$instance = new static();
            }
            return self::$instance;
        }
        /********** End **********/
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值