1.抽象工厂模式简介
抽象工厂是工厂方法的升级版,为相关或者相互依赖的对象提供一个接口,而且无效指定他们的具体实现类。
2.源码实现
/*抽象产品A*/
interface AbstractProductA {
public function getName();
}
/*抽象产品B*/
interface AbstractProductB {
public function getName();
}
/*具体产品A1*/
class ProductA1 implements AbstractProductA {
private $_name;
public function __construct()
{
$this->_name = 'Product A1';
}
public function getName()
{
return $this->_name;
}
}
/*具体产品A2*/
class ProductA2 implements AbstractProductA {
private $_name;
public function __construct()
{
$this->_name = 'Product A2';
}
public function getName()
{
return $this->_name;
}
}
/*具体产品B1*/
class ProductB1 implements AbstractProductB {
private $_name;
public function __construct()
{
$this->_name = 'Product B1';
}
public function getName()
{
return $this->_name;
}
}
/*具体产品B2*/
class ProductB2 implements AbstractProductB {
private $_name;
public function __construct()
{
$this->_name = 'Product B2';
}
public function getName()
{
return $this->_name;
}
}
/*抽象工厂*/
interface AbstractFactory {
public function createProductA();
public function createProductB();
}
/*具体工厂1*/
class ConcreteFactory1 implements AbstractFactory {
public function createProductA()
{
return new ProductA1();
}
public function createProductB()
{
return new ProductB1();
}
}
/*具体工厂2*/
class ConcreteFactory2 implements AbstractFactory {
public function createProductA()
{
return new ProductA2();
}
public function createProductB()
{
return new ProductB2();
}
}
/*客户端*/
class Client {
public static function main()
{
self::run(new ConcreteFactory1());
self::run(new ConcreteFactory2());
}
public static function run(AbstractFactory $factory)
{
$productA = $factory->createProductA();
$productB = $factory->createProductB();
echo $productA->getName()."\n";
echo $productB->getName()."\n";
}
}
Client::main();
?>
3.运行及其结果
$ php example.php
Product A1
Product B1
Product A2
Product B2