工厂模式和抽象工厂模式
2015-04-02 10:02
155 查看
区别在于,抽象工厂里一个工厂要生产多个产品,当抽象工厂生产的产品只有一个时,就叫工厂模式了。 具体来说,抽象工厂模式是工厂方法模式的升级版本,他用来创建一组相关或者相互依赖的对象。他与工厂方法模式的区别就在于,工厂方法模式针对的是一个产品等级结构;而抽象工厂模式则是针对的多个产品等级结构。在编程中,通常一个产品结构,表现为一个接口或者抽象类,也就是说,工厂方法模式提供的所有产品都是衍生自同一个接口或抽象类,而抽象工厂模式所提供的产品则是衍生自不同的接口或抽象类。
简单工厂模式跟工厂方法模式极为相似,区别是:简单工厂只有三个要素,他没有工厂接口,并且得到产品的方法一般是静态的。因为没有工厂接口,所以在工厂实现的扩展性方面稍弱,可以算所工厂方法模式的简化版。
工厂模式:
class Engine {public void getStyle(){System.out.println("这是汽车的发动机");}}class Underpan {public void getStyle(){System.out.println("这是汽车的底盘");}}class Wheel {public void getStyle(){System.out.println("这是汽车的轮胎");}}
interface IFactory {public ICar createCar();}class Factory implements IFactory {public ICar createCar() {Engine engine = new Engine();Underpan underpan = new Underpan();Wheel wheel = new Wheel();ICar car = new Car(underpan, wheel, engine);return car;}}public class Client {public static void main(String[] args) {IFactory factory = new Factory();ICar car = factory.createCar();car.show();}}抽象工厂模式:
interface IProduct1 {public void show();}interface IProduct2 {public void show();}class Product1 implements IProduct1 {public void show() {System.out.println("这是1型产品");}}class Product2 implements IProduct2 {public void show() {System.out.println("这是2型产品");}}interface IFactory {public IProduct1 createProduct1();public IProduct2 createProduct2();}class Factory implements IFactory{public IProduct1 createProduct1() {return new Product1();}public IProduct2 createProduct2() {return new Product2();}}public class Client {public static void main(String[] args){IFactory factory = new Factory();factory.createProduct1().show();factory.createProduct2().show();}}
相关文章推荐
- 设计模式(四)-工厂模式-抽象工厂模式
- 设计模式系列——三个工厂模式(简单工厂模式,工厂方法模式,抽象工厂模式)
- 工厂模式(工厂方法模式,抽象工厂模式) Java
- 我眼中的简单工厂模式,工厂模式以及抽象工厂模式
- [设计模式] - No.1 详解简单工厂模式、工厂模式和抽象工厂模式
- 工厂模式(简单工厂模式, 工厂方法模式, 抽象工厂模式)一
- 最常用的设计模式----工厂模式家族(简单工厂模式, 工厂方法模式, 抽象工厂模式)
- 《Head First 设计模式》学习笔记——工厂模式 + 抽象工厂模式
- Qt设计模式系列——三个工厂模式(简单工厂模式,工厂方法模式,抽象工厂模式)
- 工厂模式(Factory)和抽象工厂模式(Abstract Factory)
- 工厂模式(静态工厂模式、工厂方法模式、抽象工厂模式)
- 《Head First 设计模式》学习笔记——工厂模式 + 抽象工厂模式
- 简单工厂模式,工厂模式【Factory Pattern】,抽象工厂模式
- Design Patterns——Builder 模式、原型模式、工厂模式、抽象工厂模式
- 抽象工厂模式和工厂模式的差别(原创)
- 设计模式系列--工厂模式(简单工厂模式、抽象工厂模式)
- JS设计模式 - 构造函数模式,工厂模式与抽象工厂模式
- 工厂模式(简单工厂模式, 工厂方法模式, 抽象工厂模式)二
- 工厂模式(三)--抽象工厂模式
- 设计模式之创造型模式(抽象工厂模式、建造者模式、工厂模式、原型模式、单例模式)