面试题复习-常用设计模式-简单工厂模式

产品接口:

package com.ajax.pattern.simplefactory;

public interface Fruit {
    void desc();
}

产品1:

package com.ajax.pattern.simplefactory;

public class Apple implements Fruit {
    @Override
    public void desc() {
        System.out.println("苹果");
    }
}

产品2:

package com.ajax.pattern.simplefactory;

public class Orange implements Fruit {
    @Override
    public void desc() {
        System.out.println("橙子");
    }
}

工厂:

package com.ajax.pattern.simplefactory;

public class SimpleFactory {
    public static Fruit getFruit(String name) {
        switch (name) {
            case "apple":
                return new Apple();
            case "orange":
                return new Orange();
            default:
                return null;
        }
    }
}

运行:

package com.ajax.pattern.simplefactory;

public class Run {
    public static void main(String[] args) {
        SimpleFactory.getFruit("apple").desc();
    }
}

 

posted @ 2019-07-30 11:53  疯狂阿贾克斯  阅读(375)  评论(0编辑  收藏  举报