设计模式(抽象工厂)

抽象工厂(Abstract Factory)

意图:

    提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。 
适用性:

    一个系统要独立于它的产品的创建、组合和表示时。

    一个系统要由多个产品系列中的一个来配置时。

    当你要强调一系列相关的产品对象的设计以便进行联合使用时。

    当你提供一个产品类库,而只想显示它们的接口而不是实现时。

原理图:

clip_image002

实现代码:

 1 /**
 2  * 抽象工厂
 3  */
 4 interface Animal {
 5     public function createDog();
 6     public function createCat();
 7 }
 8 
 9 
10 /**
11  * 实体工厂
12  */
13 class BigFactory implements Animal {
14     public function createDog() {
15         return new bigDog();
16     }
17     public function createCat() {
18         return new bigCat();
19     }
20 }
21 
22 
23 /**
24  * 抽象产品
25  */
26 interface Big{
27     const _SIZE = 'Big ';
28     public function size();
29 }
30 /**
31  * 具体产品
32  */
33 class bigDog implements Big{
34     const ANIMAL = 'Dog';
35     public function __construct() {
36         $this->size();
37     }
38     public function size() {
39         echo self::_SIZE,self::ANIMAL,"<br>";
40     }
41 }
42 
43 class bigCat implements Big{
44     const ANIMAL = 'Cat';
45     public function __construct() {
46         $this->size();
47     }
48     public function size() {
49         echo self::_SIZE,self::ANIMAL,"<br>";
50     }
51 }
52 
53 /**
54  * 最终实例
55  */
56 $ft = new BigFactory();
57 $BigCat1 = $ft->createCat();
58 $BigCat2 = $ft->createCat();
59 
60 echo "<br>";
61 $BigDog1 = $ft->createDog();
62 $BigDog2 = $ft->createDog();

参考文献:

http://www.cnblogs.com/zhangchenliang/p/3700820.html

原文地址:https://www.cnblogs.com/faronl/p/4699347.html