php设计模式之抽象工厂模式
抽象工厂模式提供一个创建一系列相关或相互依赖对象的接口,而无须指定它们具体的类。
抽象工厂模式包含如下角色:
- AbstractFactory:抽象工厂
- ConcreteFactory:具体工厂
- AbstractProduct:抽象产品
- Product:具体产品
生产电脑
对象电脑厂是负责生产电脑来出售的。我们知道,电脑是由主机、键盘、显示器以及鼠标组成的,目前对象电脑城只生产3种电脑,低配、中配和高配的,不同配置的电脑使用的主机品牌、显示器品牌等都是不同的。
- 主机目前有:麒麟主机、雷霆主机、冬日主机
- 键盘目前有:雷柏、罗技、雷蛇
- 显示器目前有:aoc、hkc、BenQ
- 鼠标目前有:罗技、灵蛇、方正
顶配版电脑由麒麟主机、雷柏键盘、aoc显示器、罗技鼠标组成,中配由……。
关于主机的代码如下:
interface Host
{
static function createHost ();
}
class DrHost implements Host
{
public static function createHost()
{
echo '创建冬日主机' . PHP_EOL;
}
}
class QlHost implements Host
{
public static function createHost()
{
echo '创建麒麟主机' . PHP_EOL;
}
}
class LtHost implements Host
{
public static function createHost()
{
echo '创建雷霆主机' . PHP_EOL;
}
}
类似的,去创建键盘、显示器、鼠标,代码这里就不贴了。
现在,我们定义一个创建电脑的接口。
interface ComputerFactory
{
static function createHost ();
static function createKeyboard ();
static function createMonitor ();
static function createMouse ();
}
然后完成三个具体工厂用于创建低配、中配以及高配版电脑。
class GreatComputerFactory implements ComputerFactory
{
public static function createHost()
{
QlHost::createHost();
}
public static function createKeyboard()
{
LbKeyboard::createKeyboard();
}
public static function createMonitor()
{
AocMonitor::createMonitor();
}
public static function createMouse()
{
LjMouse::createMouse();
}
}
class GoodComputerFactory implements ComputerFactory
{
public static function createHost()
{
LtHost::createHost();
}
public static function createKeyboard()
{
LjKeyboard::createKeyboard();
}
public static function createMonitor()
{
HkcMonitor::createMonitor();
}
public static function createMouse()
{
LsMouse::createMouse();
}
}
class NormalComputerFactory implements ComputerFactory
{
public static function createHost()
{
DrHost::createHost();
}
public static function createKeyboard()
{
LsKeyboard::createKeyboard();
}
public static function createMonitor()
{
BenqMonitor::createMonitor();
}
public static function createMouse()
{
FzMouse::createMouse();
}
}
现在可以来创建具体的电脑了
class GreatComputer
{
public function __construct()
{
echo '高配电脑' . PHP_EOL;
GreatComputerFactory::createHost();
GreatComputerFactory::createKeyboard();
GreatComputerFactory::createMonitor();
GreatComputerFactory::createMouse();
}
}
class GoodComputer
{
public function __construct()
{
echo '中配电脑' . PHP_EOL;
GoodComputerFactory::createHost();
GoodComputerFactory::createKeyboard();
GoodComputerFactory::createMonitor();
GoodComputerFactory::createMouse();
}
}
class NormalComputer
{
public function __construct()
{
echo '低配电脑' . PHP_EOL;
NormalComputerFactory::createHost();
NormalComputerFactory::createKeyboard();
NormalComputerFactory::createMonitor();
NormalComputerFactory::createMouse();
}
}