Heim  >  Artikel  >  Backend-Entwicklung  >  Erklärung des PHP-Singleton-Modus (Codebeispiel)

Erklärung des PHP-Singleton-Modus (Codebeispiel)

不言
不言nach vorne
2018-10-24 17:30:032831Durchsuche

Der Inhalt dieses Artikels ist eine Erklärung (Codebeispiel) zum PHP-Singleton-Modus. Ich hoffe, dass er für Freunde hilfreich ist.

Das Singleton-Muster ist ein relativ häufiges Entwurfsmuster und kann in vielen Frameworks gesehen werden. Der Singleton-Modus kann sicherstellen, dass es nur eine Instanz einer Klasse gibt, wodurch die Kontrolle über die Anzahl der Instanzen erleichtert und Systemressourcen gespart werden.

<?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(&#39;Clone is not allowed !&#39;);
    }
}

Das Singleton-Muster kann mehrfach in einem System verwendet werden. Zur einfacheren Erstellung können Sie versuchen, eine allgemeine Abstraktion zu etablieren:

// 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(&#39;Clone is not allowed !&#39;);
    }
}
// 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

Das obige ist der detaillierte Inhalt vonErklärung des PHP-Singleton-Modus (Codebeispiel). Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:segmentfault.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen