抽象工厂模式
该模式属于创建型模式之一,是一种常见的软件设计模式。该模式为一个产品族提供了统一的创建接口。当需要这个产品族的某一系列的时候,可以为此系列的产品族创建一个具体的工厂类。简单理解就是定义一类产品的所有功能接口,在定义要实现每一个功能的接口,最后按照需求组合其中的功能就是抽象方法
说明
抽象工厂主要涉及四个角色
- 抽象工厂:它负责什么一个创建抽象产品的接口,通常以接口或者抽象类实现,所有的具体工厂都必须实现或继承这个类
- 具体工厂:实现了抽象工厂的具体类,客户端可以直接实例化这个类获得具体工厂操作对象
- 抽象产品:申明一类产品的接口
- 具体产品:实现了抽象产品定义的接口
优点
- 增加或者替换产品族很容易
缺点
- 难以支持新种类的产品扩展,因为抽象工厂定义产品的各种特性,如果增加新特性就需要修改所有实现该工厂的具体工厂
案例
如果我们想要生产汽车,就可以用抽象工厂来实现我们的业务逻辑,首先我们定义一个汽车的抽象工厂,这个工厂需要实现的功能有汽车空调和轮胎;然后我们再定义空调的抽象产品和轮胎的抽象产品,再实例化不同的具体产品,最后实现抽象工厂的方法就得到了各种汽车,
viewcode
/**
* 汽车抽象工厂
* Interface CarFactory
*/
interface CarFactory
{
public function createAirCondition(): AirConditionInterface;
public function createWheel(): WheelInterface;
}
/**
* 空调接口
* Interface AirConditionInterface
*/
interface AirConditionInterface
{
public function heat();
public function cold();
}
/**
* 轮胎接口
* Interface WheelInterface
*/
interface WheelInterface
{
public function run();
}
/**
* 格力空调实现空调接口
* Class GreeAirCondition
*/
class GreeAirCondition implements AirConditionInterface
{
public function cold()
{
// TODO: Implement cold() method.
echo 'gree 制冷';
}
public function heat()
{
// TODO: Implement heat() method.
echo 'gree 加热';
}
}
/**
* 海尔空调实现空调接口
* Class HireAirCondition
*/
class HireAirCondition implements AirConditionInterface
{
public function cold()
{
// TODO: Implement cold() method.
echo 'hire 制冷';
}
public function heat()
{
// TODO: Implement heat() method.
echo 'hire 加热';
}
}
/**
* 米其林实现轮胎接口
* Class MqlWheel
*/
class MqlWheel implements WheelInterface
{
public function run()
{
// TODO: Implement run() method.
echo '米其林轮胎';
}
}
/**
* 固特异轮胎实现轮胎接口
* Class GtyWheel
*/
class GtyWheel implements WheelInterface
{
public function run()
{
// TODO: Implement run() method.
echo '固特异轮胎';
}
}
/**
* 使用抽象工厂实例化Audi汽车
* Class AudiCar
*/
class AudiCar implements CarFactory
{
public function createAirCondition(): AirConditionInterface
{
// TODO: Implement createAirCondition() method.
return new GreeAirCondition();
}
public function createWheel(): WheelInterface
{
// TODO: Implement createWheel() method.
return new GtyWheel();
}
}
/**
* 使用抽象工厂实例化宝马汽车
* Class BmwCar
*/
class BmwCar implements CarFactory
{
public function createAirCondition(): AirConditionInterface
{
// TODO: Implement createAirCondition() method.
return new HireAirCondition();
}
public function createWheel(): WheelInterface
{
// TODO: Implement createWheel() method.
return new MqlWheel();
}
}
//客户端调用
class Client
{
public static function main()
{
self::run(new AudiCar());
self::run(new BmwCar());
}
private static function run(CarFactory $car)
{
$car->createAirCondition()->cold();
$car->createWheel()->run();
}
}
Client::main();