单例模式 课堂笔记

原创 2019-01-04 10:56:10 231
摘要:<?php //单例模式案例class Father{}$Father1 = new Father;$Father2 = new Father;echo ($Father1 instanceof Father)? '是':'不是';echo "<br>";echo ($Father2 instanceof Father

<?php 

//单例模式案例


class Father

{


}


$Father1 = new Father;

$Father2 = new Father;


echo ($Father1 instanceof Father)? '是':'不是';

echo "<br>";

echo ($Father2 instanceof Father)? '是':'不是';

echo "<br>";

echo ($Father1 === $Father2) ? '完全相等':'不相等';

echo "<br>";

var_dump($Father1,$Father2);



echo "<hr>";


//Mother只允许被实例化一次

class Mother{


//1. new 创建实例

//2. clone 克隆当前的实例


private function __construct(){} //构造器私有化

private function __clone(){}//克隆方法私有化



//创建类的内部静态属性,保存类的唯一实例

protected static $instance = null;



//创建一个外部接口,并返回当前类的唯一实例

public static function getInstance(){

if (is_null(static :: $instance)){

static :: $instance = new static();

}

return static :: $instance;

}


}

//从外部进行实例化


$Mother1 = Mother :: getInstance();

$Mother2 = Mother :: getInstance();

echo ($Mother1 instanceof Mother)? '是':'不是';

echo "<br>";

echo ($Mother2 instanceof Mother)? '是':'不是';

echo "<br>";

echo ($Mother1 === $Mother2) ? '完全相等':'不相等';

echo "<br>";

var_dump($Mother1,$Mother2);



 ?>


批改老师:韦小宝批改时间:2019-01-04 11:01:18
老师总结:写的很不错!设计模式在以后的大项目开发中使用是非常频繁的!课后一定要多练习!

发布手记

热门词条