PHP 设计模式极简介绍

工厂方法模式
通过工厂类的方法去创建并返回产品对象。
 
class Factory {

    public function create(){

        return new Product();
    }

}

class Product { }

(new Factory())->create();
 
抽象工厂模式
抽象工厂用来统每个工厂的标准,具体工厂里的方法根据型号生产不同产品。
 
interface AbstractFactory {
    public function create(string $type);
}

public class Factory implements AbstractFactory {

    public create(string type) {

        switch (type) {
            case "circle":
                return new CircleProduct();
            default:
                return null;
        }

    }

}

class CircleProduct {

}


(new Factory())->create('circle');
 
单例模式
保证一个类全局只有一个实例,并提供全局访问点。实现方式有两种:饿汉式和懒汉式。
饿汉式在类加载时,立即创建了唯一实例,而不管有没有使用。
懒汉式在第一次调用时才创建唯一实例,避免内存浪费,要注意多线程同步问题,避免出现多个实例。
 
class Singleton {

    private static $instance = null;

    private function __construct() {}

    public static getInstance() {

        if(self::$instance == null){
            self::$instance = new static();
        }

        return self::$instance;
    }
}


$singleton =  Singleton::getInstance();
 
建造者模式
指挥者控制建造者去创建产品。
 
// 指挥者
class Director {

    public make(Builder $builder) {

        $builder->buildColor();
    }
}

// 建造者
class Builder {

    public __construct() {
        $this->product = new Product();
    }

    public buildColor(){
        $this->product->setColor('red');
    }

}

//产品类
class Product {
    public function setColor(string $color){
        this->color = color;
    }

}


$director = new Director();
$director->make(new Builder());
 
原型模式
复制现有对象来创建新对象。
 
class Prototype {

    public function __clone(){

        $new = new self();
        $new->name = "副本";
        return $new;

    }

}


$obj = clone (new Prototype())
 
适配器模式
协调接口不兼容的对象一起工作。
 
// 被适配者
class Adaptee {

    public void runing() {
        echo "I am running!"
    }
}

// 适配器
class Adapter {

    public function __construct(Adaptee adaptee){
        $this->adaptee = adaptee;
    }

    public function run(){
        $this->adaptee->running();
    }

}


$target = new Adapter(new Adaptee());
$target.run();
 
桥接模式
将产品的各个部分独立出来,以方便它们能自由组装在一起,创建不同属性的产品。
 
class BossCar {

    public function __construct($engine) {
          $this->engine = $engine;
    }

    public fucntion getBrand() {
        return "Boss";
    }

    public fucntion drive() {
        $this->engine->start();
        echo "Drive " . $this->getBrand() . " car...";
    }
}

class ElectricEngine {
    public function start() {
        System.out.println("Start Hybrid Engine...");
    }
}

class FuelEngine {
    public function start() {
        System.out.println("Start Hybrid Engine...");
    }
}


(new BossCar(new FuelEngine()))->drive(); // 燃油车
(new BossCar(new ElectricEngine()))->drive();// 电动车
 
组合模式
将同一类型对象组合成在一起,形成树形结构。
 
// 抽象构件
interface Component {
    public operation();
}

// 树枝构件
class Branch implements Component {

    public function add(Component c) {
        $this->child[] = c
    }

    public function operation() {

        echo "This is a Branch object.";
        foreach ($this->child as c) {
            c.operation();
        }
    }
}

//Leaf 叶子构件
class Leaf implements Component {

    public function operation() {
       echo "This is a Leaf object.";
    }

}


$leaf = new Leaf();
$branch1 = new Branch();
$branch1.add(leaf);

$branch2 = new Branch();
$branch2.add($branch1)

$branch2.operation(); //从组合对象开始遍历整颗树
 
装饰器模式
以层层嵌套的方式,扩展一个对象。
 
interface TextNode {

    public function setText($text);
    public function getText();
}

// 被装饰对象
class SpanNode implements TextNode {

    public function __construct(string $text){

        $this->text = $text;
    }

    public void setText(string $text) {
        $this->text = $text;
    }

    public String getText() {
        return "<span>" + $this->text + "</span>";
    }
}


//装饰器:加粗
class BoldDecorator extends TextNode {

    public function __construct(TextNode $target) {
        $this->target = $target;
    }

    public String getText() {
        return "<b>" + target.getText() + "</b>";
    }
}

//装饰器:斜体
class UnderlineDecorator extends TextNode {

    public function __construct(TextNode $target) {
        $this->target = $target;
    }

    public String getText() {
        return "<i>" + target.getText() + "</i>";
    }
}

$node = new BoldDecorator(new UnderlineDecorator(new SpanNode("Hello")));
$node->getText();

外观模式
将原本复杂的调用过程封装起来,对外提供一个简单的调用。本质上就是又封装了一层。
 
 
享元模式
缓存对象,以便共享。创建对象时,先从缓存取,缓存不存在时,再创建并缓存。
 
class Student {

    public static $cache = [];

    public function __construct($id, $name) {
        $this->id = $id;
        $this->name = $name;
    }

    public static function create($id, $name){

        $key = $id . ":" . $name;
        $student = self::$cache[$key];

        if ($student == null) {
            $student = new self($id, $name);
            self::$cache[$key] = $student;
        }
        return $student;
    }

}


Student::create(1, 'tom');
Student::create(2, 'jim');
 
代理模式
给对象提供一个代理,以控制对该对象的访问。分为动态代理和静态代理。
 
class File {
    public function read($file) {
        return file_get_contents($file);
    }
}

class Proxy {

    public function __construct($object) {
        $this->object = $object;
    }

    public function read($file) {

        if (!$this->isAllowed()) {
            throw new Exception("Access denied!");
        }

        return $this->object->read($file);
    }

    private function isAllowed($file) {
        return true;
    }

}

$proxy = new Proxy(new File());
$proxy->read('a.txt');

 

责任链模式
一条请求在责任链路中进行传递,直到被处理。
 
abstract class Leader {

    protected $next = null;

    public function __construct(Leader $next){
        $this->next = $next
    }

    public abstract function handle(int $days);

    public function nextHandle(){
        if($this->next){
            $this->next->handle();
        }else{
            throw new Exception("无法处理该请求");
        }
    }

}

class ClassAdviser extends Leader {

    public function handle(int $days){
        if($days <= 2){
            echo "班主任批准请假" . $days . "天。";
        }else{
            $this->nextHandle($days); //交给上级领导处理
        }
    }
}

class DepartmentHead extends Leader {

    public function handle(int $days){
        if($days <= 7){
            echo "系主任批准请假" . $days . "天。";
        }else{
            $this->nextHandle($days); //交给上级领导处理
        }
    }
}


leader = new ClassAdviser(new DepartmentHead());
leader.handle(5);//请假5天

 

命令模式

将一个对象中的方法封装成命令对象,实现调用方法名称统一。
class Editor {

    public function copy() {
        echo "已复制!"
    }
    public function paste() {
        echo "已粘贴!"
    }

}

abstract class Command {

    public function __construct(Editor $editor){
        $this->editor = $editor
    }

    public abstract function execute();
}

class Copy extends Command {

    public void execute() {
        $this->editor->copy();
    }
}

class Paste extends Command {

    public void execute() {
        $this->editor->paste();
    }

}

$editor = new Editor();

$command = new Copy($editor);
$command->execute();

$command = new Paste($editor);
$command->execute();
 
posted @ 2023-05-26 20:24  心随所遇  阅读(13)  评论(0编辑  收藏  举报