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. 缺点
工厂方法模式仿佛已经很完美地对对象的创建进行了包装,使得客户程序中仅仅处理抽象产品角色提供的接口,但使得对象的数量成倍增长。当产品种类非常多时,会出现大量的与之对应的工厂对象,这不是很好,于是就有了抽象工厂模式。
欲知抽象工厂模式如何?且听下回分解。