简介
工厂方法中,每一个具体工厂类都对应创建一个具体产品类,所有具体工厂类都实现抽象工厂,所有具体产品类都实现抽象产品。
抽象工厂定义了创建抽象产品的方法签名,具体工厂类各自实现各自逻辑,来创建具体的产品。
角色
类图
如图所示,Dialog 抽象工厂可以创建 Button 抽象产品,WindowsDialog 和 WebDialog 都是具体工厂,负责创建 WindownsButton 和 HTMLButton。
代码
abstract class Creator
{
abstract public function factoryMethod(): Product;
public function someOperation(): string
{
$product = $this->factoryMethod();
$result = "Creator: The same creator's code has just worked with " . $product->operation();
return $result;
}
}
class ConcreteCreator1 extends Creator
{
public function factoryMethod(): Product
{
return new ConcreteProduct1();
}
}
class ConcreteCreator2 extends Creator
{
public function factoryMethod(): Product
{
return new ConcreteProduct2();
}
}
interface Product
{
public function operation(): string;
}
class ConcreteProduct1 implements Product
{
public function operation(): string
{
return "{Result of the ConcreteProduct1}";
}
}
class ConcreteProduct2 implements Product
{
public function operation(): string
{
return "{Result of the ConcreteProduct2}";
}
}
function clientCode(Creator $creator)
{
echo "Client: I'm not aware of the creator's class, but it still works.\n" . $creator->someOperation() . "\n";
}
echo "App: Launched with the ConcreteCreator1.\n";
clientCode(new ConcreteCreator1());
echo "App: Launched with the ConcreteCreator2.\n";
clientCode(new ConcreteCreator2());
复制代码
output
App: Launched with the ConcreteCreator1.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with {Result of the ConcreteProduct1}
App: Launched with the ConcreteCreator2.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with {Result of the ConcreteProduct2}
复制代码
评论