当前位置:网站首页>Simple Factory Pattern

Simple Factory Pattern

2022-08-09 06:28:00 The koala over rice

简单工厂模式

From simple plant role(创造者),抽象产品(所有具体产品的父类,可以是接口或者抽象类),具体产品(Succession or implement specific products)三个组成

具体实现

public class Test {
    
    // 相当于客户端
    public static void main(String[] args) {
    
        // 首先创建工厂,Through the factory to create the corresponding class again
        Factory factory = new Factory();
        factory.getCar("wulin").name();
        factory.getCar("dazong").name();
    }

    // 抽象产品
    interface Car {
    
        void name();
    }
    // 具体产品
    static class Dazong implements Car {
    
        @Override
        public void name() {
    
            System.out.println("this is dazong");
        }
    }
    // 具体产品
    static class Wulin implements Car {
    
        @Override
        public void name() {
    
            System.out.println("this is wulin");
        }
    }

    // 简单工厂
    static class Factory {
    
        // By calling the factory get entity method to create specific products,Return to the abstract specific products
        public Car getCar(String car){
    
            switch (car){
    
                case "wulin":
                    return new Wulin();
                case "dazong":
                    return new Dazong();
            }
            return null;
        }
    }
}
原网站

版权声明
本文为[The koala over rice]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090622259220.html