• 工厂方法模式


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

    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();
            
        }

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

  • 相关阅读:
    转:理想主义终结年代的七种兵器
    基础地理空间框架
    coldplay 全集下载
    S40 用google sync同步通讯录(转)
    分享一个关于Steve Jobs演讲的分析
    转:我们时代的思想责任与尊严
    nginx 视频流
    vue 使用路由重复跳转同一页面
    批处理文件编写
    ZBB – ZERO Bug Bounce
  • 原文地址:https://www.cnblogs.com/51life/p/9605670.html
Copyright © 2020-2023  润新知