设计模式: 工厂模式,使对象有一个统一生成(实例化)的入口。 简单工厂,也称静态工厂的例子:
class Factory
{
public static function createProduct(string $type) : Product
{
$product = null;
switch ($type) {
case 'A':
$product = new ProductA();
break;
case 'B':
$product = new ProductB();
break;
}
return $product;
}
}
产品接口和产品实现
interface Product
{
public function show();
}
class ProductA implements Product
{
public function show()
{
echo 'Show ProductA';
}
}
class ProductB implements Product
{
public function show()
{
echo 'Show ProductB';
}
}
$productA = Factory::createProduct('A');
$productB = Factory::createProduct('B');
$productA->show();
$productB->show();
单例模式:
class Singleton{
private static $instance;
private function __construct(){}
public $a;
public static function getInstance(){
if(!(self::$instance instanceof self)){
self::$instance = new self();
}
return self::$instance;
}
private function __clone(){}
}
发布订阅模式
<?php
interface Observer
{
function notify($msg);
}
class User implements Observer {
public $name;
public function __construct($name) {
$this->$name = $name;
Msg::getInstance()->register($this);
}
public function notify($msg) {
echo $this->name . ' '. 'recive msg' .$msg.'\r\n';
}
}
class Msg
{
private $obeservers = [];
private static $_instance ;
public static function getInstance()
{
if(!self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
public function publish($msg) {
foreach ($this->observers as $observer) {
$observer->notify($msg);
}
}
function register(Observer $o) {
$this->observers[] = $o;
}
}
$user1 = new User('xushengbin');
$user2 = new User('zhuqiaozhen');
$msg = Msg::getInstance()->publish('今天要下雨了');
参考文献: [1] PHP设计模式之简单工厂模式 ZyBlog 硬核项目经理
|