创建型模式:
单例模式、工厂模式(简单工厂、工厂方法、抽象工厂)、创建者模式、原型模式。
1、单例模式
目的:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
应用场景:数据库连接、缓存操作、分布式存储。
<?php/**** 单例模式**/class DbConn{private static $_instance = null;protected static $_counter = 0;protected $_db;//私有化构造函数,不允许外部创建实例private function __construct(){self::$_counter += 1;}public function getInstance(){if (self::$_instance == null){self::$_instance = new DbConn();}return self::$_instance;}public function connect(){echo "connected: ".(self::$_counter)."n";return $this->_db;}}/** 不使用单例模式时,删除构造函数的private后再测试,第二次调用构造函数后,_counter变成2*/// $conn = new DbConn();// $conn->connect();// $conn = new DbConn();// $conn->connect();//使用单例模式后不能直接new对象,必须调用getInstance获取$conn = DbConn::getInstance();$db = $conn->connect();//第二次调用是同一个实例,_counter还是1$conn = DbConn::getInstance();$db = $conn->connect();?>
复制代码
特别说明:这里getInstance里有if判断然后再生成对象,在多线程语言里是会有并发问题的。例如java的解决方案有二个,给方法加上synchronized关键词变成同步,或者把_instanc的初始化提前放到类成员变量定义时,但是这2种方式php都不支持。不过因为php不支持多线程所以不需要考虑这个问题了。
2、工厂模式
实现:定义一个用于创建对象的接口,让子类决定实例化哪一个类。
应用场景:众多子类并且会扩充、创建方法比较复杂。
<?php/*** 工厂模式**///抽象产品interface Person {public function getName();}//具体产品实现class Teacher implements Person {function getName() {return "老师n";}}class Student implements Person {function getName() {return "学生n";}}//简单工厂class SimpleFactory {public static function getPerson($type) {$person = null;if ($type == 'teacher') {$person = new Teacher();} elseif ($type == 'student') {$person = new Student();}return $person;}}//简单工厂调用class SimpleClient {function main() {// 如果不用工厂模式,则需要提前指定具体类// $person = new Teacher();// echo $person->getName();// $person = new Student();// echo $person->getName();// 用工厂模式,则不需要知道对象由什么类产生,交给工厂去决定$person = SimpleFactory::getPerson('teacher');echo $person->getName();$person = SimpleFactory::getPerson('student');echo $person->getName();}}//工厂方法interface CommFactory {public function getPerson();}//具体工厂实现class StudentFactory implements CommFactory {function getPerson(){return new Student();}}class TeacherFactory implements CommFactory {function getPerson() {return new Teacher();}}//工厂方法调用class CommClient {static function main() {$factory = new TeacherFactory();echo $factory->getPerson()->getName();$factory = new StudentFactory();echo $factory->getPerson()->getName();}}//抽象工厂模式另一条产品线interface Grade {function getYear();}//另一条产品线的具体产品class Grade1 implements Grade {public function getYear() {return '2003级';}}class Grade2 implements Grade {public function getYear() {return '2004级';}}//抽象工厂interface AbstractFactory {function getPerson();function getGrade();}//具体工厂可以产生每个产品线的产品class Grade1TeacherFactory implements AbstractFactory {public function getPerson() {return new Teacher();}public function getGrade() {return new Grade1();}}class Grade1StudentFactory implements AbstractFactory {public function getPerson() {return new Student();}public function getGrade() {return new Grade1();}}class Grade2TeacherFactory implements AbstractFactory {public function getPerson() {return new Teacher();}public function getGrade() {return new Grade2();}}//抽象工厂调用class FactoryClient {function printInfo($factory) {echo $factory->getGrade()->getYear().$factory->getPerson()->getName();}function main() {$client = new FactoryClient();$factory = new Grade1TeacherFactory();$client->printInfo($factory);$factory = new Grade1StudentFactory();$client->printInfo($factory);$factory = new Grade2TeacherFactory();$client->printInfo($factory);}}//简单工厂//SimpleClient::main();//工厂方法//CommClient::main();//抽象工厂FactoryClient::main();?>
复制代码
三种工厂的区别是,抽象工厂由多条产品线,而工厂方法只有一条产品线,是抽象工厂的简化。而工厂方法和简单工厂相对,大家初看起来好像工厂方法增加了许多代码但是实现的功能和简单工厂一样。但本质是,简单工厂并未严格遵循设计模式的开闭原则,当需要增加新产品时也需要修改工厂代码。但是工厂方法则严格遵守开闭原则,模式只负责抽象工厂接口,具体工厂交给客户去扩展。在分工时,核心工程师负责抽象工厂和抽象产品的定义,业务工程师负责具体工厂和具体产品的实现。只要抽象层设计的好,框架就是非常稳定的。
3、创建者模式
在创建者模式中,客户端不再负责对象的创建与组装,而是把这个对象创建的责任交给其具体的创建者类,把组装的责任交给组装类,客户端支付对对象的调用,从而明确了各个类的职责。
应用场景:创建非常复杂,分步骤组装起来。
<?php/*** 创建者模式*///购物车class ShoppingCart {//选中的商品private $_goods = array();//使用的优惠券private $_tickets = array();public function addGoods($goods) {$this->_goods[] = $goods;}public function addTicket($ticket) {$this->_tickets[] = $ticket;}public function printInfo() {printf("goods:%s, tickets:%sn", implode(',', $this->_goods), implode(',', $this->_tickets));}}//假如我们要还原购物车的东西,比如用户关闭浏览器后再打开时会根据cookie还原$data = array('goods' => array('衣服', '鞋子'),'tickets' => array('减10'),);//如果不使用创建者模式,则需要业务类里一步步还原购物车// $cart = new ShoppingCart();// foreach ($data['goods'] as $goods) {// $cart->addGoods($goods);// }// foreach ($data['tickets'] as $ticket) {// $cart->addTicket($ticket);// }// $cart->printInfo();// exit;//我们提供创建者类来封装购物车的数据组装class CardBuilder {private $_card;function __construct($card) {$this->_card = $card;}function build($data) {foreach ($data['goods'] as $goods) {$this->_card->addGoods($goods);}foreach ($data['tickets'] as $ticket) {$this->_card->addTicket($ticket);}}function getCrad() {return $this->_card;}}$cart = new ShoppingCart();$builder = new CardBuilder($cart);$builder->build($data);echo "after builder:n";$cart->printInfo();?>
复制代码
可以看出,使用创建者模式对内部数据复杂的对象封装数据组装过程后,对外接口就会非常简单和规范,增加修改新数据项也不会对外部造成任何影响。
3、 原型模式
用原型实例指定创建对象的种类,并且通过拷贝这个原型来创建新的对象。
应用场景: 类的资源非常多、性能和安全要求,一般和工厂方法结合使用。
<?php/*** 原型模式*///声明一个克隆自身的接口interface Prototype {function copy();}//产品要实现克隆自身的操作class Student implements Prototype {//简单起见,这里没有使用get setpublic $school;public $major;public $name;public function __construct($school, $major, $name) {$this->school = $school;$this->major = $major;$this->name = $name;}public function printInfo() {printf("%s,%s,%sn", $this->school, $this->major, $this->name);}public function copy() {return clone $this;}}$stu1 = new Student('清华大学', '计算机', '张三');$stu1->printInfo();$stu2 = $stu1->copy();$stu2->name = '李四';$stu2->printInfo();?>
复制代码
这里可以看到,如果类的成员变量非常多,如果由外部创建多个新对象再一个个赋值,则效率不高代码冗余也容易出错,通过原型拷贝复制自身再进行微小修改就是另一个新对象了。
创建型模式就总结完了。下面还有两部分结构型设计模式和行为型设计模式稍后继续。
来源:oschina
链接:https://my.oschina.net/u/1420250/blog/669033
