工厂方法模式

工厂方法模式是对简单工厂模式的进一步解耦,在工厂方法模式中,一个具体的产品类对应一个工厂类,这些工厂类都是实现同一个工厂接口。可以理解为一个工厂只生产一种产品。还是拿水果举例:在简单工厂模式中,一家水果店卖好几种水果,但在工厂方法模式中,一家水果店只能卖一种水果,比如苹果店只卖苹果,橘子店只卖橘子。

1.创建产品接口和产品类

创建Fruit(产品接口)

public interface Fruit {
    //对水果的描述
    void describe();
}

创建Apple(具体产品类)

public class Apple implements Fruit{
    public void describe() {
        System.out.println("I am Apple");
    }
}

创建Orange(具体产品类)

public class Orange implements Fruit{
    public void describe() {
        System.out.println("I am Orange");
    }
}

2.创建工厂接口和工厂类

创建FruitFactory(工厂接口)

/**
 * @author chenyk
 * @date 2018年9月7日
 * 工厂接口:水果店接口
 */

public interface FruitFactory {
    Fruit createFruit();
}

创建AppleFactory(具体工厂类)

public class AppleFactory implements FruitFactory{
    public Fruit createFruit() {
        return new Apple();
    }
}

创建OrangeFactory (具体工厂类)

public class OrangeFactory implements FruitFactory{
    public Fruit createFruit() {
        return new Orange();
    }
}

好了,准备工作做好了,那么假如顾客想买Apple和Orange怎么办?

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        //创建工厂类
        FruitFactory appleFactory = (FruitFactory) Class.forName("com.demo.designModel.AppleFactory").newInstance();
        FruitFactory orangeFactory = (FruitFactory) Class.forName("com.demo.designModel.OrangeFactory").newInstance();
        
        // 根据工厂类获取产品对象
        Fruit apple = appleFactory.createFruit();
        Fruit orange = orangeFactory.createFruit();
        
        //调用产品对象的方法
        apple.describe();
        orange.describe();
        
    }

总结:工厂方法模式其实就是针对每个产品都对应一个工厂,该工厂只生产对应的该一种产品。当每增加一种产品时,同时需要新增对应的一个工厂类。

posted @ 2018-09-07 16:41  51life  阅读(178)  评论(0编辑  收藏  举报