单例模式:
实例
<meta charset="UTF-8"> <?php class Config { //用来判断是否被实例化 private static $instance = null; //用户的自定义配置 private $setting = []; //不允许外部实例化 private function __construct() { } //不允许从外部克隆对象 private function __clone() { } //创建当前唯一实例 public static function getInstance() { //判断是否被实例化 if(self::$instance == null) { self::$instance = new self(); } return self::$instance; } //设置配置项 public function set($index,$value) { $this->setting[$index] = $value; } public function get($index) { return $this->setting[$index]; } } //实例化 //构造器被私有化不能用new $obj = Config::getInstance(); $obj->set('host','localhost'); echo $obj->get('host');
运行实例 »
点击 "运行实例" 按钮查看在线实例
工厂模式:
实例
<?php class Shape { //声明静态方法create,根据内容不同,创建不同的实例 public static function create($type,array $size=[]) { //判断内容 switch ($type) { case 'rectangle': //如果是长方形就直接实例化new Rectangle return new Rectangle($size[0],$size[1]); break; case 'triangle': return new Triangle($size[0],$size[1]); break; } } } class Rectangle { private $width; private $height; public function __construct($witch,$height) { $this->width = $witch; $this->height = $height; } //长 * 高 public function area() { return $this->width * $this->height; } } class Triangle { private $bottom; //底 private $height; //长 public function __construct($bottom,$height) { $this->bottom = $bottom; $this->height = $height; } //长 * 高 / 2 public function area() { return ($this->bottom * $this->height)/2; } } //用静态方法实例化 $restangle = Shape::create('rectangle',[20,50]); echo $restangle->area(); $triangle = Shape::create('triangle',[20,50]); echo $triangle->area();
运行实例 »
点击 "运行实例" 按钮查看在线实例
注册树:
实例
<?php class Demo1{} class Demo2{} class Demo3{} class Register { //创建一个静态容器保存对象 public static $objs = []; //挂载 索引 对象 public static function set($index,$obj) { self::$objs[$index] = $obj; } //读取 public static function get($index) { return self::$objs[$index]; } //销毁 public static function del($index) { unset(self::$objs[$index]); } } //实例化 Register::set('demo1',new Demo1); Register::set('demo2',new Demo2); Register::set('demo3',new Demo3); var_dump(Register::get('demo2')); //销毁 Register::del('demo2'); var_dump(Register::get('demo2'));
运行实例 »
点击 "运行实例" 按钮查看在线实例