工厂方法的精髓是在工厂里面有一个创建对象的方法,对象的创建与使用相分离
对象都实现了相同的接口
我们按照如下UML类图实现代码
1) 对象都实现的方法
1public interface Moveable {
2 void go();
3}
2) 创建Car Plane Broom三个对象
1public class Car implements Moveable {
2
3 public void go() {
4 System.out.println("Car go wuwuwuwuw....");
5 }
6}
1public class Plane implements Moveable {
2 public void go() {
3 System.out.println("plane flying shushua....");
4 }
5}
1public class Broom implements Moveable{
2
3 @Override
4 public void go() {
5 System.out.println("broom flying chuachuachua .....");
6 }
7}
3) 创建对象工厂负责生产对象
1public class CarFactory {
2 public Moveable create() {
3 System.out.println("a car created!");
4 return new Car();
5 }
6}
说到工厂方法,想到了另一种模式,简单工厂方法模式,这不是23种设计模式之一,因为它的扩展性不好
1/** 2 * 简单工厂的可扩展性不好 3 */
4public class SimpleVehicleFactory {
5 public Car createCar() {
6 //before processing
7 return new Car();
8 }
9
10 public Broom createBroom() {
11 return new Broom();
12 }
13}
工厂方法模式的主要优点有:
用户只需要知道具体工厂的名称就可得到所要的产品,无须知道产品的具体创建过程;
在系统增加新的产品时只需要添加具体产品类和对应的具体工厂类,无须对原工厂进行任何修改,满足开闭原则;