zoukankan      html  css  js  c++  java
  • 工厂方法模式

    简单工厂模式有一个问题,就是只能通过工厂代码构造特定的类型的对象。如果对象添加一个种类,那么必须修改工厂的代码。这样违背了开闭原则,因此我们讲解工厂方法模式

    工厂方法模式是将工厂抽取出一个父类来,里面有一个创造对象的方法,每造一种对象写一个对应的子类工厂。这样新增子类对象就不会修改原来的代码了。

    代码实现:

    package com.zhen.build_template.factory_method;
    
    /**
     * @author zhen
     * @Date 2019/5/28 11:13
     */
    public interface Sender {
        public void send();
    }
    
    package com.zhen.build_template.factory_method;
    
    /**
     * @author zhen
     * @Date 2019/5/28 11:13
     */
    public class MailSender implements Sender {
        @Override
        public void send() {
            System.out.println("this is mailSender");
        }
    }
    
    package com.zhen.build_template.factory_method;
    
    /**
     * @author zhen
     * @Date 2019/5/28 11:14
     */
    public class SmsSender implements Sender {
        @Override
        public void send() {
            System.out.println("this is SmsSender");
        }
    }
    
    package com.zhen.build_template.factory_method;
    
    /**
     * @author zhen
     * @Date 2019/5/28 11:32
     */
    public interface SendFactory {
        Sender getSenderInstance();
    }
    
    package com.zhen.build_template.factory_method;
    
    /**
     * @author zhen
     * @Date 2019/5/28 11:33
     */
    public class SendMailFactory implements SendFactory {
        @Override
        public Sender getSenderInstance() {
            return new MailSender();
        }
    }
    
    package com.zhen.build_template.factory_method;
    
    /**
     * @author zhen
     * @Date 2019/5/28 11:36
     */
    public class SendSmsFactory implements SendFactory {
        @Override
        public Sender getSenderInstance() {
            return new SmsSender();
        }
    }
    工厂方法模式代码
  • 相关阅读:
    python之道04
    python之list [ 列表 ]
    end和sep的使用方法
    pass1
    python之for (循环)
    python之range (范围)
    python之str (字符型)
    python之bool (布尔值)
    python之int (整型)
    python之道03
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/10942282.html
Copyright © 2011-2022 走看看