工厂模式

2020-04-26  本文已影响0人  virsus

简单工厂

public class FactoryMode {
  interface Product {
        void hello();
    }

    static class Product1 implements Product {

        @Override
        public void hello() {
            System.out.println("hello,Product1");
        }
    }
    static class Product2 implements Product {

        @Override
        public void hello() {
            System.out.println("hello,Product2");
        }
    }

    static class SimpleFactory {
        public static Product getProduct(String type) {
            if ("1".equals(type)) {
                return new Product1();
            }
            if ("2".equals(type)) {
                return new Product2();
            } else {
                return null;
            }
        }
    }
    public static void main(String[] args) {
        Product product = SimpleFactory.getProduct("1");
        product.hello();
    }
}

工厂方法

public class FactoryMode {
    interface Factory {
        Product create();
    }
    interface Product {
        void hello();
    }

    static class Factory1 implements Factory {

        @Override
        public Product create() {
            return new Product1();
        }
    }
    static class Factory2 implements Factory {

        @Override
        public Product create() {
            return new Product2();
        }
    }

    static class Product1 implements Product {

        @Override
        public void hello() {
            System.out.println("hello,Product1");
        }
    }
    static class Product2 implements Product {

        @Override
        public void hello() {
            System.out.println("hello,Product2");
        }
    }

    public static void main(String[] args) {
        Factory factory = new Factory1();
        Product product = factory.create();
        product.hello();
    }
}

工厂方法跟简单工厂的组合

static class FactoryMap {
        private static final Map<String,Factory> map = new HashMap<>();
        static {
            map.put("1",new Factory1());
            map.put("2",new Factory2());
        }
        public static Factory getFactory(String type) {
            if (StringUtils.isEmpty(type)) {
                return null;
            }
            return map.get(type);
        }
    }

    public static void main(String[] args) {
        Factory factory = FactoryMap.getFactory("1");
        Product product = factory.create();
        product.hello();
    }

总结

上一篇 下一篇

猜你喜欢

热点阅读