工厂方法模式
通过工厂类的方法去创建并返回产品对象。
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();