java设计模式--创建型模式--抽象工厂

什么是抽象工厂,再次学习。

 1                                         抽象工厂
 2  概述
 3     提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
 4     
 5  适用性
 6     1.一个系统要独立于它的产品的创建、组合和表示时。
 7 
 8     2.一个系统要由多个产品系列中的一个来配置时。
 9 
10     3.当你要强调一系列相关的产品对象的设计以便进行联合使用时。
11 
12     4.当你提供一个产品类库,而只想显示它们的接口而不是实现时。
13              参与者
14     1.AbstractFactory
15       声明一个创建抽象产品对象的操作接口。
16 
17     2.ConcreteFactory
18       实现创建具体产品对象的操作。
19 
20     3.AbstractProduct
21       为一类产品对象声明一个接口。
22 
23     4.ConcreteProduct
24       定义一个将被相应的具体工厂创建的产品对象。
25       实现AbstractProduct接口。
26 
27     5.Client
28       仅使用由AbstractFactory和AbstractProduct类声明的接口
29  

测试类:

 1 public class test {
 2     public static void main(String[] args) {
 3         IAnimalFactory blackAnimalFactory = new BlackAnimalFactory();
 4         ICat blackCat = blackAnimalFactory.createCat();
 5         blackCat.eat();
 6         IDog blackDog = blackAnimalFactory.createDog();
 7         blackDog.eat();
 8 
 9         IAnimalFactory whiteAnimalFactory = new WhiteAnimalFactory();
10         ICat whiteCat = whiteAnimalFactory.createCat();
11         whiteCat.eat();
12         IDog whiteDog = whiteAnimalFactory.createDog();
13         whiteDog.eat();
14     }
15 
16 }
1 public interface IAnimalFactory {
2 
3     ICat createCat();
4     
5     IDog createDog();
6 }
 1 public class BlackAnimalFactory implements IAnimalFactory {
 2 
 3     public ICat createCat() {
 4         return new BlackCat();
 5     }
 6 
 7     public IDog createDog() {
 8         return new BlackDog();
 9     }
10 
11 }
1 public interface ICat {
2 
3     void eat();
4 }
1 public class BlackCat implements ICat {
2 
3     public void eat() {
4         System.out.println("The black cat is eating!");
5     }
6 
7 }
1 public class WhiteCat implements ICat {
2 
3     public void eat() {
4         System.out.println("The white cat is eating!");
5     }
6 
7 }

 

posted @ 2014-10-23 14:27  全力以赴001  阅读(381)  评论(0编辑  收藏  举报