使用抽象工厂模式,根据不同的条件返回不同的工厂对象。
实现代码如下:
// 定义一个抽象工厂接口
interface AbstractFactory {
public function createProductA();
public function createProductB();
}
// 实现具体工厂类
class ConcreteFactoryForType1 implements AbstractFactory {
public function createProductA() {
return new ProductType1A();
}
public function createProductB() {
return new ProductType1B();
}
}
class ConcreteFactoryForType2 implements AbstractFactory {
public function createProductA() {
return new ProductType2A();
}
public function createProductB() {
return new ProductType2B();
}
}
// 定义抽象产品接口
interface AbstractProductA {
public function usefulFunctionA(): string;
}
interface AbstractProductB {
public function usefulFunctionB(): string;
}
// 实现具体产品类
class ProductType1A implements AbstractProductA {
public function usefulFunctionA(): string {
return "The result of the product A1.";
}
}
class ProductType1B implements AbstractProductB {
public function usefulFunctionB(): string {
return "The result of the product B1.";
}
}
class ProductType2A implements AbstractProductA {
public function usefulFunctionA(): string {
return "The result of the product A2.";
}
}
class ProductType2B implements AbstractProductB {
public function usefulFunctionB(): string {
return "The result of the product B2.";
}
}
// 客户端代码,根据不同条件调用不同的工厂来获取不同类型的对象
$clientCode = function (AbstractFactory $factory) {
$productA = $factory->createProductA();
$productB = $factory->createProductB();
echo $productA->usefulFunctionA() . "
";
echo $productB->usefulFunctionB() . "
";
};
// 调用客户端代码
$clientCode(new ConcreteFactoryForType1());
$clientCode(new ConcreteFactoryForType2());