批改狀態(tài):合格
老師批語:
單例模式
<?php /** * User: Z先生 * Date: 2018/5/10 * 單例模式 */ class Config { /* * 聲明一個(gè)靜態(tài)的私有屬性,保存當(dāng)前類實(shí)例 */ private static $data = null; private $arr = []; //構(gòu)造器私有化,克隆方法私有化 private function __construct(){} private function __clone(){} //創(chuàng)建唯一實(shí)例 public static function one() { if(self::$data == null){ self::$data = new self(); } return self::$data; } //設(shè)置配置項(xiàng) public function set($index, $value) { $this->arr[$index] = $value; } //讀取配置項(xiàng) public function get($index) { return $this->arr[$index]; } } $a =Config::one(); $b =Config::one(); var_dump($a,$b); echo '<hr>'; $b->set('name','123'); echo $b->get('name');
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
工廠模式
<?php /** * User: Z先生 * Date: 2018/5/10 * 注冊(cè)樹模式 * 將類放到數(shù)組中 */ class A1{} class A2{} class A3{} class Register { //創(chuàng)建空的數(shù)組 public static $arr=[]; //將對(duì)象掛載到樹上 public static function set($index,$value) { self::$arr[$index] = $value; } //將對(duì)象取出 public static function get($index) { return self::$arr[$index]; } //將對(duì)象銷毀 public static function dlt($index) { unset(self::$arr[$index]); } } //將早先的三個(gè)類掛載到樹上 Register::set('a1',new A1); Register::set('a2',new A2); Register::set('a3',new A3); //檢查是否掛到了樹上 var_dump(Register::$arr); echo '<hr>'; //拿出來看看 var_dump(Register::get('a3')); echo '<hr>'; //拿出來吃一個(gè) Register::dlt('a3'); var_dump(Register::get('a3'));
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
注冊(cè)樹模式
<?php /** * User: Z先生 * Date: 2018/5/10 * 工廠模式 */ class sg { public static function jg($data,$arr) { switch ($data) { case '蘋果': return new Apple($arr); break; case '香蕉': return new Banner($arr); break; } } } class Apple { private $num; private $money = 6.9; public function __construct($arr) { return $this->num = $arr; } public function get() { return $this->num * $this->money; } } class Banner { private $num; private $money = 4.5; public function __construct($arr) { return $this->num = $arr; } public function get() { return $this->num * $this->money; } } $a = sg::jg('蘋果',6); echo $a->get();
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)