补交作业:
单例模式代码:
实例
<?php class Db { private static $instance; private function __construct($sql) { $this->sql=$sql; echo '我被实例化了!'.'<br>'; } private function __clone() { } public static function getInstance($sql){ // 用is_null进行判断 // if(is_null(self::$instance)) // 用instanceof进行判断 if(!self::$instance instanceof Db) { self::$instance=new self($sql); } return self::$instance; } public function query(){ echo $this->sql; } } //第一次实例化 $db=Db::getInstance('SELECT * FROM user'); $db->query(); echo '<hr>'; //第二次实例化 $data=Db::getInstance('DELETE * FROM staff'); $data->query(); echo '<hr>'; var_dump($db,$data);
运行实例 »
点击 "运行实例" 按钮查看在线实例
工厂模式代码:
实例
<?php class Person { public static function human($color) { switch ($color){ case 'black': return new Blackman($color); break; case 'white': return new Whiteman($color); break; } } } class Blackman{ private $color; public function __construct($color) { $this->color=$color; } public function special(){ echo '黑色人种,地处非洲,语言为法语、英语。'; } } class Whiteman{ private $color; public function __construct($color) { $this->color=$color; } public function special(){ echo '白色人种,地处美洲和欧洲,语言为英语。'; } } $person=Person::human('black'); echo $person->special(); echo '<hr>'; $person=Person::human('white'); echo $person->special();
运行实例 »
点击 "运行实例" 按钮查看在线实例
注册模式代码:
实例
<?php class Register { public static $objects; public static function set($index,$object){ self::$objects[$index]=$object; } public static function get($index){ if(isset(self::$objects[$index])) return self::$objects[$index]; echo '对象实例不存在!'; } public static function _unset($index){ unset(self::$objects[$index]); } } class Demo{ public function test(){ echo '正确执行!'; } } //实例化 $demo=new Demo(); //注册 $uptree=Register::set('index',$demo); //读取 $read=Register::get('index'); //测试 $read->test(); //销毁 Register::_unset('index');
运行实例 »
点击 "运行实例" 按钮查看在线实例