php基本设计模式(单例、工厂、注册器)
=================
工厂 单例 注册 ... ...
-----------------------------
工厂模式 是用工厂方法代替new操作的一种模式。
<?php class TESTA { public function say() { echo "hello"; } } class Factory { public static function newTestA() { return new TESTA(); } } $obj = Factory::newTestA(); $obj->say();
工厂方法的案例:
<?php abstract class Operation { protected $paramA = 0; protected $paramB = 0; protected $result = 0; public function __construct($a , $b) { $this->paramA = $a; $this->paramB = $b; } abstract protected function getResult(); } class AddOpt extends Operation { public function getResult() { $this->result = $this->paramA + $this->paramB; return $this->result; } } class SubOpt extends Operation { public function getResult() { $this->result = $this->paramA - $this->paramB; return $this->result; } } class Factoryone { // private static $obj; 这样写不对!!! public static function optNum($type , $a ,$b) { if( $type === '+') { return new AddOpt($a,$b); } if( $type === '-' ) { // self::$obj = return new SubOpt($a,$b);; return new SubOpt($a,$b); } } } $obj = Factoryone::optNum( '-' , 7,5); echo $obj->getResult();
工厂模式文章:
htp://www.cnblogs.com/hongfei/archive/2012/07/07/2580776.html
http://www.cnblogs.com/wangtao_20/p/3594192.html
单例
<?php class Database { protected static $ins; private function __construct() {} public static function getInstance() { if(self::$ins) { }else{ self::$ins = new self(); } return self::$ins; } public function linkMysql() { return "mysql"; } } $db = Database::getInstance(); echo $db->linkMysql();
思路; private 构造方法禁止new, 写静态方法供外部调用, 在类内部实例化存到静态变量中, 判断是否被实例化过。
注册器模式
<?php class Register { protected static $reg = []; public static function selfset($name , $ins) { self::$reg[$name] = $ins; } public static function selfget($name) { return self::$reg[$name]; } public static function selunset($name) { unset(self::$reg[$name]); } } class DB { public function showDB() { echo "showDB --"; } } $db = new DB(); Register::selfset('hello' , $db); $dbone = Register::selfget('hello'); $dbone->showDB();
全局共享和交换对象的类
使用: 工厂方法中进行调用单例实现数据库链接, 单例生成数据库对象后, 直接调用 register::set() 将它注册在 register 中。
则在任何其他的类中要使用 这个只要进行 Register::get('db');就可以取出这个对象的实例

浙公网安备 33010602011771号