二十三种设计模式之创建型模式之抽象工厂
2015-09-06 13:56
309 查看
抽象工厂
概述提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
适用性
1.一个系统要独立于它的产品的创建、组合和表示时。 2.一个系统要由多个产品系列中的一个来配置时。 3.当你要强调一系列相关的产品对象的设计以便进行联合使用时。 4.当你提供一个产品类库,而只想显示它们的接口而不是实现时。
参与者
1.AbstractFactory 声明一个创建抽象产品对象的操作接口。 2.ConcreteFactory 实现创建具体产品对象的操作。 3.AbstractProduct 为一类产品对象声明一个接口。 4.ConcreteProduct 定义一个将被相应的具体工厂创建的产品对象。 实现AbstractProduct接口。 5.Client 仅使用由AbstractFactory和AbstractProduct类声明的接口
类图
例子
AbstractFactory
public interface IAnimalFactory { ICat createCat(); IDog createDog(); }
ConcreteFactory
public class BlackAnimalFactory implements IAnimalFactory { public ICat createCat() { return new BlackCat(); } public IDog createDog() { return new BlackDog(); } } public class WhiteAnimalFactory implements IAnimalFactory { public ICat createCat() { return new WhiteCat(); } public IDog createDog() { return new WhiteDog(); } }
AbstractProduct
public interface ICat { void eat(); } public interface IDog { void eat(); }
ConcreteProduct
public class BlackCat implements ICat { public void eat() { System.out.println("The black cat is eating!"); } } public class WhiteCat implements ICat { public void eat() { System.out.println("The white cat is eating!"); } } public class BlackDog implements IDog { public void eat() { System.out.println("The black dog is eating"); } } public class WhiteDog implements IDog { public void eat() { System.out.println("The white dog is eating!"); } }
Client
public static void main(String[] args) { IAnimalFactory blackAnimalFactory = new BlackAnimalFactory(); ICat blackCat = blackAnimalFactory.createCat(); blackCat.eat(); IDog blackDog = blackAnimalFactory.createDog(); blackDog.eat(); IAnimalFactory whiteAnimalFactory = new WhiteAnimalFactory(); ICat whiteCat = whiteAnimalFactory.createCat(); whiteCat.eat(); IDog whiteDog = whiteAnimalFactory.createDog(); whiteDog.eat(); }
result
The black cat is eating! The black dog is eating! The white cat is eating! The white dog is eating!
Copyright © 2008 Angus Young
疯狂Java联盟:http://www.crazyit.org
相关文章推荐
- Python动态类型的学习---引用的理解
- PropertyChangeListener简单理解
- 什么是设计模式
- 设计模式之创建型模式 - 特别的变量问题
- 七、设计模式——装饰模式
- 设计模式总结
- 设计模式之创建型模式
- 浅谈设计模式的学习
- Draw Something,以何种魅力征服大众
- 一步一步跟我学易语言之第二个易程序菜单设计
- 土人系列AS入门教程 -- 对象篇
- C#托管堆对象实例包含内容分析
- javascript asp教程第十一课--Application 对象
- PowerShell中使用Out-String命令把对象转换成字符串输出的例子
- VBS教程:对象-正则表达式(RegExp)对象
- 基于逻辑运算的简单权限系统(原理,设计,实现) VBS 版
- C#检查指定对象是否存在于ArrayList集合中的方法
- C#中设计、使用Fluent API