国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 PHP源碼 PHP singleton pattern implementation

PHP singleton pattern implementation

Nov 09, 2016 pm 02:28 PM

<?php


 * Class Singleton
 * 單例模式,也叫單子模式,是一種常用的軟件設(shè)計模式。在應(yīng)用這個模式時,單例對象的類必須保證只有一個實(shí)例存在,
 * 充分體現(xiàn)了 DRY(Don&#39;t Repeat Yourself)的思想。
 *
 * 實(shí)現(xiàn)單例模式的思路是:一個類能返回對象一個引用(永遠(yuǎn)是同一個)和一個獲得該實(shí)例的方法(必須是靜態(tài)方法,通常使用getInstance這個名稱);
 * 當(dāng)我們調(diào)用這個方法時,如果類持有的引用不為空就返回這個引用,如果類保持的引用為空就創(chuàng)建該類的實(shí)例并將實(shí)例的引用賦予該類保持的引用;
 * 同時我們還將該類的構(gòu)造函數(shù)定義為私有方法,這樣其他處的代碼就無法通過調(diào)用該類的構(gòu)造函數(shù)來實(shí)例化該類的對象,只有通過該類提供的靜態(tài)方法來得到該類的唯一實(shí)例。
 *
 * 應(yīng)用場景:適用于一個類只有一個實(shí)例的場景。數(shù)據(jù)庫連接,日志記錄,購物車
 * 缺點(diǎn):PHP運(yùn)行是頁面級別的,無法直接實(shí)現(xiàn)跨頁面的內(nèi)存數(shù)據(jù)共享。
 */
class Singleton
{
    //保存類實(shí)例的私有的靜態(tài)成員變量
    private static $_instance;
    //私有的構(gòu)造方法
    private function __construct()
    {
        echo &#39;This is a Constructed method;&#39;;
    }
    //創(chuàng)建一個空的私有__clone方法防止對象被克隆
    private function __clone()
    {
    }
    //單例方法,用于獲取唯一的實(shí)例對象
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            //instanceof用于檢測對象與類的從屬關(guān)系,is_subclass_of對象所屬類是否類的子類
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    //測試
    public function test()
    {
        echo 123;
    }
}
$a = Singleton::getInstance();
$a->test();
echo PHP_EOL;
$b = Singleton::getInstance(); //第二次調(diào)用時不執(zhí)行構(gòu)造方法
$b->test();
echo PHP_EOL;
//$c=new Singleton();由于構(gòu)造方法私有,這個會報錯的
//$d=clone $a;克隆對象報錯

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)