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

JAVA设计模式是个什么玩意儿_01_工厂方法模式

2016-10-19 15:50 381 查看

1. 前言

工厂方法模式(Factory Method)

该模式属于创建型设计模式。

2. 定义

 摘自《研磨设计模式》 陈臣、王斌



3.代码举例

public interface BMW {

public void run();
}

public class BMWX3 implements BMW {

public void run() {
System.out.println("宝马x3在路上奔跑……");
}
}

public class BMWX5 implements BMW {

public void run() {
System.out.println("宝马x5在路上奔跑……");
}
}

public interface BMWFactory {
public BMW createBMW();
}

public class BMWX3Factory implements BMWFactory {

public BMW createBMW() {
return new BMWX3();
}
}

public class BMWX5Factory implements BMWFactory {

public BMW createBMW() {
return new BMWX5();
}
}

public class Client {

public static void main(String[] args) {
BMWFactory bmwx3Factory = new BMWX3Factory();
BMW bmwx3 = bmwx3Factory.createBMW();
bmwx3.run();

BMWFactory bmx5Factory = new BMWX5Factory();
BMW bmwx5 = bmx5Factory.createBMW();
bmwx5.run();
}
}

输出结果:
宝马x3在路上奔跑……
宝马x5在路上奔跑……

4. 缺点

       工厂方法模式仿佛已经很完美地对对象的创建进行了包装,使得客户程序中仅仅处理抽象产品角色提供的接口,但使得对象的数量成倍增长。当产品种类非常多时,会出现大量的与之对应的工厂对象,这不是很好,于是就有了抽象工厂模式。

       

       欲知抽象工厂模式如何?且听下回分解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息