批改状态:未批改
老师批语:
<?php
/*单例模式:一个类仅允许创建一个实例
*/
class Config
{
/*
必须先创建一个私有静态属性并且赋值为null,
*/
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;
}
}
/*
工厂模式:用于创建多种类型的多个实例对象
*/
class Shape
{
public static function create($type,array $size=[])
{
swich($type)
{
//长方形
case 'retangle':
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;
}
}
/*
* 注册树:其实就是创建一个对象集,也叫对象池,是用数组来进行存储的
* 原理非常的简单
*/
//先声明三个类,一会丢进对象树上中
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::$objs);
echo '<hr>';
echo '<pre>'.print_r(Register::$objs,true).'</pre>';
echo '<hr>';
//用注册类的get方法查看
var_dump(Register::get('demo2'));
//删除对象池中的某个实例对象
Register::del('demo2');
//再次查看demo2对象,已经不能被查看了,因为被销毁了
var_dump(Register::get('demo2'));点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号