您的位置:首页 > 编程语言 > Java开发

工厂模式和抽象工厂模式

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
相关文章推荐