1. 程式人生 > >單例模式(防繼承,防克隆)

單例模式(防繼承,防克隆)

<?php

//單列模式

// //1.普通類
// class singleton{

// }

// $s1 = new singleton();
// $s2 = new singleton();
// //注意,2個變數是同1個物件的時候才全等
// if ($s1 === $s2) {
//     echo '是一個物件';
// }else{
//     echo '不是一個物件';
// }



// //2.封鎖new操作
// class singleton{
//     protected function __construct(){}
// }
// $s1 = new singleton();//PHP Fatal error:  Call to protected singleton::__construct() 


// //3.留個介面來new物件
// class singleton{
//     protected function __construct(){}

//     public  static function getIns(){
//         return new self();
//     }
// }

// $s1 =  singleton::getIns();
// $s2 =  singleton::getIns();
// if ($s1 === $s2) {
//     echo '是一個物件';
// }else{
//     echo '不是一個物件';
// }

// //4.getIns先判斷例項
// class singleton{

//     protected static $ins = null;

//     private function __construct(){}

//     public  static function getIns(){
//         if (self::$ins === null) {
//             self::$ins = new self();
//         }
//         return self::$ins;
//     }
// }

// $s1 =  singleton::getIns();
// $s2 =  singleton::getIns();
// if ($s1 === $s2) {
//     echo '是一個物件';
// }else{
//     echo '不是一個物件';
// }

// //繼承
// class A extends singleton{
//     public function __construct(){}
// }
// echo '<br>';
// $s1 =  new A();
// $s2 =  new A();
// if ($s1 === $s2) {
//     echo '是同一個物件';
// }else{
//     echo '不是同一個物件';
// }


// //5.防止繼承時被修改了許可權
// class singleton{

//     protected static $ins = null;

//     //方法加final則方法不能被覆蓋,類加final則類不能被繼承
//     final private function __construct(){}

//     public  static function getIns(){
//         if (self::$ins === null) {
//             self::$ins = new self();
//         }
//         return self::$ins;
//     }
// }

// $s1 =  singleton::getIns();
// $s2 =  singleton::getIns();
// if ($s1 === $s2) {
//     echo '是同一個物件';
// }else{
//     echo '不是同一個物件';
// }

// //繼承
// // class A extends singleton{
// //     public function __construct(){}
// // }
// //Cannot override final method singleton::__construct()

// echo '<hr>';
// $s1 =  singleton::getIns();
// $s2 =  clone $s1;
// if ($s1 === $s2) {
//     echo '是同一個物件';
// }else{
//     echo '不是同一個物件';
// }


//6.防止被clone
class singleton{

    protected static $ins = null;

    //方法加final則方法不能被覆蓋,類加final則類不能被繼承
    final private function __construct(){}

    public  static function getIns(){
        if (self::$ins === null) {
            self::$ins = new self();
        }
        return self::$ins;
    }

    // 封鎖clone
    final private function __clone(){}
}

$s1 =  singleton::getIns();
$s2 =  clone $s1; //Call to private singleton::__clone() from context
if ($s1 === $s2) {
    echo '是同一個物件';
}else{
    echo '不是同一個物件';
}