批改状态:合格
老师批语:
单例
<?php
/**
* Created by PhpStorm.
* User: 金超
* Date: 2018/5/11
* Time: 15:58
*/
class config{
// 声明一个私有属性 保存当前实例
private static $data=null;
private $method=[];
//将构造器,克隆私有化
private function __construct()
{
}
private function __clone()
{
// TODO: Implement __clone() method.
}
// 创造唯一实例
public static function first()
{
if(self::$data==null){
self::$data=new self();
}
return self::$data;
}
//设置配置项
public function set($index,$value)
{
$this->method[$index]=$value;
}
public function get($index)
{
return $this->method[$index];
}
}
$test1=config::first();
$test2=config::first();
echo'<pre>';
var_dump($test1,$test2);
echo'<hr>';
$test2->set('kim','25');
echo $test2->get('kim');点击 "运行实例" 按钮查看在线实例
工厂模式
<?php
/**
* Created by PhpStorm.
* User: 金超
* Date: 2018/5/11
* Time: 16:25
*/
class band{
public static function create($level,array $size=[])
{
//检查level
switch ($level)
{
//low
case'low';
return new Low($size[0],$size[1]);
break;
case 'middle';
return new Middle($size[0],$size[1]);
case 'high';
return new high($size[0],$size[1]);
}
}
}
class Low{
private $height;
private $width;
public function __construct($height,$width)
{
$this->height=$height;
$this->width=$width;
}
public function price()
{
return($this->height*$this->width)*1.3.'元';
}
}
class Middle{
private $height;
private $width;
public function __construct($height,$width)
{
$this->height=$height;
$this->width=$width;
}
public function price()
{
return($this->height*$this->width)*2.7.'元';
}
}
class High{
private $height;
private $width;
public function __construct($height,$width)
{
$this->height=$height;
$this->width=$width;
}
public function price()
{
return($this->height*$this->width)*3.68.'元';
}
}
$Low=band::create('low',[10,38]);
echo'品级为low,长宽为[10,38]的价格为'.$Low->price();
echo'<hr>';
$Middle=band::create('middle',[10,38]);
echo'品级为middle,长宽为[17,29]的价格为'.$Middle->price();
echo'<hr>';
$High=band::create('high',[10,38]);
echo'品级为high,长宽为[9,11]的价格为'.$High->price();点击 "运行实例" 按钮查看在线实例
注册树
<?php
/**
* Created by PhpStorm.
* User: 金超
* Date: 2018/5/11
* Time: 16:42
*/
class planA{};
class planB{};
class planC{};
class Register //声明对象注册树类
{ //静态属性中保存着所有已经挂载到树上的对象
public static $plans=[];
//将对象挂载到树上
public static function set($index,$plan)
{
self::$plans[$index]=$plan;
}
//取出对象使用
public static function get($index)
{
return self::$plans[$index];
}
//销毁无效的对象
public static function del($index)
{
unset(self::$plans[$index]);
}
}
//将三个类实例并挂到树上
Register::set('planA',new planA());
Register::set('planB',new planB());
Register::set('planC',new planC());
//检查是否上树
echo'<pre>';
var_dump(Register::$plans);
echo '<hr>';
//删除planA 并查看结果
Register::del('planA');
var_dump(Register::get('planA'));点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号