抽象工厂模式

抽象工厂模式(Abstract Factory Pattern)是一种创建型设计模式,它允许你创建一系列相关的对象,而无需指定其具体类。

在PHP中,可以使用抽象类和接口来实现抽象工厂模式。

1、定义一个抽象工厂类,其中包含用于创建产品的抽象方法:

abstract class AbstractFactory {
    abstract public function createProductA();
    abstract public function createProductB();
}

2,创建具体的工厂类,继承抽象工厂类并实现其中的抽象方法:

class ConcreteFactory1 extends AbstractFactory {
    public function createProductA() {
        return new ProductA1();
    }
    public function createProductB() {
        return new ProductB1();
    }
}
class ConcreteFactory2 extends AbstractFactory {
    public function createProductA() {
        return new ProductA2();
    }
    public function createProductB() {
        return new ProductB2();
    }
}

3,定义产品类,并在具体工厂类中实例化它们:

interface ProductA {
    public function doSomething();
}
interface ProductB {
    public function doSomethingElse();
}
class ProductA1 implements ProductA {
    public function doSomething() {
        echo "Product A1 does something.\n";
    }
}
class ProductB1 implements ProductB {
    public function doSomethingElse() {
        echo "Product B1 does something else.\n";
    }
}
class ProductA2 implements ProductA {
    public function doSomething() {
        echo "Product A2 does something.\n";
    }
}
class ProductB2 implements ProductB {
    public function doSomethingElse() {
        echo "Product B2 does something else.\n";
    }
}
$factory1 = new ConcreteFactory1();
$productA1 = $factory1->createProductA();
$productB1 = $factory1->createProductB();
$factory2 = new ConcreteFactory2();
$productA2 = $factory2->createProductA();
$productB2 = $factory2->createProductB();
$productA1->doSomething();
$productB1->doSomethingElse();
$productA2->doSomething();
$productB2->doSomethingElse();

以上代码中,我们定义了两个具体工厂类:

ConcreteFactory1和 ConcreteFactory2,它们分别创建了

ProductA1、ProductB1和 ProductA2、ProductB2这四个产品。我们通过这四个产品的实例化来验证抽象工厂模式的实现。

输出结果为:

Product A1 does something.
Product B1 does something else.
Product A2 does something.
Product B2 does something else.
评论

0 条评论