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

    工厂方法模式即父类定义接口,具体的实现交给子类来做,从而提供开闭原则

    /**
     * @author maikec
     * @date 2019/5/10
     */
    public abstract class AbstractFactory {
        /**
         * 创建产品
         * @param owner
         * @return AbstractProduct
         */
        protected abstract AbstractProduct createProduct(String owner);
    
        /**
         * 把产品注入数组
         * @param product
         */
        protected abstract void registerProduct(AbstractProduct product);
    
        /**
         * 创建产品并注入列表
         * @return
         */
        public final AbstractProduct create(String owner){
            AbstractProduct product = createProduct(owner);
            registerProduct(product);
            return product;
        }
    }
    
    /**
     * @author maikec
     * @date 2019/5/10
     */
    public abstract class AbstractProduct {
        /**
         * 使用
         */
        public abstract void use();
    }
    
    /**
     * @author maikec
     * @date 2019/5/10
     */
    public class IDCardFactory extends AbstractFactory {
        private final List<IDCard> idCards = new LinkedList<>(  );
        @Override
        protected AbstractProduct createProduct(String owner) {
            if (null == owner){
                throw new IllegalArgumentException( "owner cannot be null" );
            }
            return new IDCard( owner );
        }
    
        @Override
        protected void registerProduct(AbstractProduct product) {
            if (!(product instanceof IDCard)){
                throw new IllegalArgumentException( "product should be IDCard instance" );
            }
            idCards.add( (IDCard) product );
        }
    }
    
    /**
     * @author maikec
     * @date 2019/5/10
     */
    public class IDCard extends AbstractProduct {
        public IDCard(String owner){
            this.owner = owner;
        }
        private String owner;
    
        public String getOwner() {
            return owner;
        }
    
        @Override
        public void use() {
            System.out.println( "This is " + owner + " IDCard" );
        }
    }
    
    /**
     * @author maikec
     * @date 2019/5/10
     */
    public class FactoryMethodDemo {
        public static void main(String[] args) {
            AbstractFactory factory = new IDCardFactory();
            AbstractProduct product = factory.create( "Maikec" );
            product.use();
        }
    }

    附录

    https://github.com/maikec/pattern 个人GitHub设计模式案例

    声明

    引用该文档请注明出处

  • 相关阅读:
    AtCoder Grand Contest 031
    CF1010D Mars rover
    51Nod 1317 相似字符串对
    upd
    查漏补缺——字符串www.qq.com所有非空子串
    c语言查漏补缺——Win32环境下动态链接库(DLL)编程原理
    编程——二维矩阵中1所构成的块个数(孤岛问题)
    使用Windows自带远程桌面应用连接CentOS8远程桌面
    ZeroTier + NoMachine
    WinPE装入硬盘做应急系统教程
  • 原文地址:https://www.cnblogs.com/imaikce/p/10903101.html
Copyright © 2011-2022 走看看