六大原则
1.单一职责
2.里氏代换原则
3.依赖倒置原则
4.接口隔离原则
5.迪米特原则
设计模式分类
创建型模式: 工厂模式(简单工厂 工厂方法 抽象工厂)
结构型模式:适配器模式 门面模式 装饰器模式 注册树模式 代理模式 管道模式
行为型模式:策略模式 观察者模式 命令模式 迭代器模式
单例模式
定义:保证一个类只有一个实例,并提供一个访问它的全局访问点。
三私一共
class Singleton
{
//创建静态私有的变量保存该类对象
static private $instance;
//防止使用new直接创建对象
private function __construct(){}
//防止使用clone克隆对象
private function __clone(){}
static public function getInstance()
{
//判断$instance是否是Singleton的对象,不是则创建
if (!self::$instance instanceof self) {
self::$instance = new self();
}
return self::$instance;
}
public function test()
{
echo "我是一个单例模式";
}
}
$sing = Singleton::getInstance();
$sing->test();
$sing2 = new Singleton(); //Fatal error: Uncaught Error: Call to private Singleton::__construct() from invalid context in
$sing3 = clone $sing; //Fatal error: Uncaught Error: Call to private Singleton::__clone() from context
简单工厂
使用场景:支付、数据库连接
缺点:扩展时违反开闭原则 需要改动类源码
DbMysql class
{
public function conn()
{
echo '链接mysql';
}
}
DbSqlite class
{
public function conn()
{
echo '链接Sqlite';
}
}
DbSql class
{
public statis function start($type)
{
swotch ($type)
{
case : 'mysql'
return new DbMsql();
break;
case : 'sqlite'
return new BbSqlite()
break;
default :
echo '没有此类'
}
}
}
工厂方法模式
定义:工厂方法就是为了解决简单工厂扩展性的问题
接口类:interface 是为了规范调用类的方法必须与接口类方法一致
interface Db
{
public function conn();
}
DbMysql class implements Db
{
public function conn()
{
echo '连接mysql';
}
}
DbSqlite class implements Db
{
public function conn()
{
echo '连接sqlite';
}
}
==扩展==
DbOracle class implements Db
{
public function conn()
{
echo '连接oracle';
}
}
===================生产================
interface Factory
{
public static function createNew();
}
mysqlFactory class implements Factory
{
public static function createNew()
{
return new DbMysql;
};
}
sqlliteFactory class implements Factory
{
public static function createNew()
{
return new DbSqlite;
};
}
==扩展==
oracleFactory class implements Factory
{
public static function createNew()
{
return new DbOracle;
};
}
==========调用===========
//调用mysql
$mysql = mysqlFactory::createNew();
$mysql->conn();
//调用sqlite
$sqlite = sqliteFactory::createNew();
$sqlite ->conn();
//调用oracle
$oracle = mysqlFactory::createNew();
$oracle->conn();
抽象工厂模式
定义:用来生产不同产品的组合
缺点:扩展性不好,对于新增无能为力
<?php
interface Product
{
public function calculatePrice(): int;
}// Product{} end
class ShippableProduct implements Product
{
/*
* @var float
*/
private $shippingCosts;
public function __construct(int $productPrice, int $shippingCosts)
{
$this->productPrice = $productPrice;
$this->shippingCosts = $shippingCosts;
}
public function calculatePrice(): int
{
return $this->productPrice + $this->shippingCosts;
}// calculatePrice() end
}// ShippableProduct{} end
class DigitalProduct implements Product
{
/**
* @var int
*/
private $price;
public function __construct(int $price)
{
$this->price = $price;
}
public function calculatePrice(): int
{
return $this->price;
}// calculatePrice() end
}// DigitalProduct{} end
class ProductFactory
{
const SHIPPING_COSTS = 50;
public function createShippableProduct(int $price): Product
{
return new ShippableProduct($price, self::SHIPPING_COSTS);
}// createShippableProduct() end
public function createDigitalProduct(int $price): Product
{
return new DigitalProduct($price);
}// createDigitalProduct() end
}// ProductFactory{} end
$factory = new ProductFactory();
$product = $factory->createDigitalProduct(150);
print_r($product);
/*
DigitalProduct Object
(
[price:DigitalProduct:private] => 150
)
*/
$product = $factory->createShippableProduct(150);
print_r($product);
/*
ShippableProduct Object
(
[shippingCosts:ShippableProduct:private] => 50
[productPrice] => 150
)
适配器模式
定义:将一个类的接口,转换成客户期望的另一个类的接口。适配器让原本接口不兼容的类可以合作无间
类适配器使用的是继承:
/**
* 目标角色
*/
interface Target {
/**
* 源类也有的方法1
*/
public function sampleMethod1();
/**
* 源类没有的方法2
*/
public function sampleMethod2();
}
/**
* 源角色
*/
class Adaptee {
/**
* 源类含有的方法
*/
public function sampleMethod1() {
echo 'Adaptee sampleMethod1 <br />';
}
}
/**
* 类适配器角色
*/
class Adapter extends Adaptee implements Target {
/**
* 源类中没有sampleMethod2方法,在此补充
*/
public function sampleMethod2() {
echo 'Adapter sampleMethod2 <br />';
}
}
class Client {
/**
* Main program.
*/
public static function main() {
$adapter = new Adapter();
$adapter->sampleMethod1();
$adapter->sampleMethod2();
}
}
对象适配器使用的是委派:
/**
* 目标角色
*/
interface Target {
/**
* 源类也有的方法1
*/
public function sampleMethod1();
/**
* 源类没有的方法2
*/
public function sampleMethod2();
}
/**
* 源角色
*/
class Adaptee {
/**
* 源类含有的方法
*/
public function sampleMethod1() {
echo 'Adaptee sampleMethod1 <br />';
}
}
/**
* 类适配器角色
*/
class Adapter implements Target {
private $_adaptee;
public function __construct(Adaptee $adaptee) {
$this->_adaptee = $adaptee;
}
/**
* 委派调用Adaptee的sampleMethod1方法
*/
public function sampleMethod1() {
$this->_adaptee->sampleMethod1();
}
/**
* 源类中没有sampleMethod2方法,在此补充
*/
public function sampleMethod2() {
echo 'Adapter sampleMethod2 <br />';
}
}
class Client {
/**
* Main program.
*/
public static function main() {
$adaptee = new Adaptee();
$adapter = new Adapter($adaptee);
$adapter->sampleMethod1();
$adapter->sampleMethod2();
}
}
装饰器模式
定义:
1.装饰器模式(Decorator),可以动态地添加修改类的功能
2.一个类提供了一项功能,如果要在修改并添加额外的功能,传统的编程模式,需要写一个子类继承它,并重新实现类的方法
3.使用装饰器模式,仅需在运行时添加一个装饰器对象即可实现,可以实现最大的灵活性
<?php
/**
* 输出一个字符串
* 装饰器动态添加功能
* Class EchoText
*/
class EchoText
{
protected $decorator = [];
public function Index()
{
//调用装饰器前置操作
$this->beforeEcho();
echo "你好,我是装饰器。";
//调用装饰器后置操作
$this->afterEcho();
}
//增加装饰器
public function addDecorator(Decorator $decorator)
{
$this->decorator[] = $decorator;
}
//执行装饰器前置操作 先进先出原则
protected function beforeEcho()
{
foreach ($this->decorator as $decorator)
$decorator->before();
}
//执行装饰器后置操作 先进后出原则
protected function afterEcho()
{
$tmp = array_reverse($this->decorator);
foreach ($tmp as $decorator)
$decorator->after();
}
}
/**
* 装饰器接口
* Class Decorator
*/
interface Decorator
{
public function before();
public function after();
}
/**
* 颜色装饰器实现
* Class ColorDecorator
*/
class ColorDecorator implements Decorator
{
protected $color;
public function __construct($color)
{
$this->color = $color;
}
public function before()
{
echo "<dis style='color: {$this->color}'>";
}
public function after()
{
echo "</div>";
}
}
/**
* 字体大小装饰器实现
* Class SizeDecorator
*/
class SizeDecorator implements Decorator
{
protected $size;
public function __construct($size)
{
$this->size = $size;
}
public function before()
{
echo "<dis style='font-size: {$this->size}px'>";
}
public function after()
{
echo "</div>";
}
}
//实例化输出类
$echo = new EchoText();
//增加装饰器
$echo->addDecorator(new ColorDecorator('red'));
//增加装饰器
$echo->addDecorator(new SizeDecorator('22'));
//输出
$echo->Index();
注册数模式
定义:解决全局共享和交换对象。已经创建好的对象,挂在到某个全局可以使用的数组上,在需要使用的时候,直接从该数组上获取即可。将对象注册到全局的树上。任何地方直接去访问
<?php
class Register
{
protected static $objects;
//注册
function set($alias,$object)//将对象注册到全局的树上 (别名,对象)
{
self::$objects[$alias]=$object;//将对象放到树上
}
//获取
static function get($name){
return self::$objects[$name];//获取某个注册到树上的对象
}
//销毁
function _unset($alias)
{
unset(self::$objects[$alias]);//移除某个注册到树上的对象。
}
}
门面模式
定义:为子系统中的一组接口提供一个一致的界面,Facade模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
<?php
class Send
{
private $aliYunService;
private $jiGuangService;
private $message;
private $push;
public function __construct()
{
$this->aliYunService = new AliYunService();
$this->jiGuangService = new JiGuangService();
$this->message = new MessageInfo();
$this->push = new PushInfo();
}
public function PushAndSendAliYun()
{
$this->message->Send($this->aliYunService);
$this->push->Push($this->aliYunService);
}
public function PushAndSendJiGuang()
{
$this->message->Send($this->jiGuangService);
$this->push->Push($this->jiGuangService);
}
}
class MessageInfo
{
public function Send($service)
{
$service->Send();
}
}
class PushInfo
{
public function Push($service)
{
$service->Push();
}
}
class AliYunService
{
public function Send()
{
echo '发送阿里云短信!', PHP_EOL;
}
public function Push()
{
echo '推送阿里云通知!', PHP_EOL;
}
}
class JiGuangService
{
public function Send()
{
echo '发送极光短信!', PHP_EOL;
}
public function Push()
{
echo '推送极光通知!', PHP_EOL;
}
}
$send = new Send();
$send->PushAndSendAliYun();
$send->PushAndSendJiGuang();