抽象工厂模式

类图

2024061217355536.png

需要的产品和工厂

使用工厂方法模式实现

已有代码的基础上,还需要新增以下代码

 
// 抽象产品
interface Checkbox
{
public function render();
}
 
// 具体产品1
class WinCheckbox implements Checkbox
{
public function render()
{
return "Render a Checkbox in Windows style.";
}
}
 
// 具体产品2
class MacCheckbox implements Checkbox
{
public function render()
{
return "Render a Checkbox in macOS style.";
}
}
 
// 抽象工厂
abstract class CheckboxFactory
{
abstract public function createCheckbox(): Checkbox;
}
 
// 具体工厂1
class WinCheckboxFactory extends CheckboxFactory
{
public function createCheckbox(): Checkbox
{
return new WinCheckbox();
}
}
 
// 具体工厂2
class MacCheckboxFactory extends CheckboxFactory
{
public function createCheckbox(): Checkbox
{
return new MacCheckbox();
}
}

这个时候存在的问题:

改进后的代码

<?php
 
// 抽象产品
interface Button
{
public function render();
}
 
// 抽象产品
interface Checkbox
{
public function render();
}
 
// 具体产品1
class WinButton implements Button
{
public function render()
{
return "Render a button in Windows style.";
}
}
 
// 具体产品2
class MacButton implements Button
{
public function render()
{
return "Render a button in macOS style.";
}
}
 
// 具体产品1
class WinCheckbox implements Checkbox
{
public function render()
{
return "Render a Checkbox in Windows style.";
}
}
 
// 具体产品2
class MacCheckbox implements Checkbox
{
public function render()
{
return "Render a Checkbox in macOS style.";
}
}
 
 
interface GUIFactory
{
public function createButton(): Button;
public function createCheckbox(): Checkbox;
}
 
class WinFactory implements GUIFactory
{
public function createButton(): Button
{
return new WinButton();
}
 
public function createCheckbox(): Checkbox
{
return new WinCheckbox();
}
}
 
class MacFactory implements GUIFactory
{
public function createButton(): Button
{
return new MacButton();
}
 
public function createCheckbox(): Checkbox
{
return new MacCheckbox();
}
}
 
// 客户端
function client(GUIFactory $factory)
{
$button = $factory->createButton();
$checkbox = $factory->createCheckbox();
 
echo $button->render() . PHP_EOL;
echo $checkbox->render() . PHP_EOL;
}
 
client(new WinFactory());
client(new MacFactory());