天天看点

Java设计模式--简单工厂模式

简单工厂模式,又称为静态方法工厂模式。结构图如下:

Java设计模式--简单工厂模式

 实现:

水果接口:

package com.design.simplefactory;

public interface Fruit {

    String fruitName();
}      

实现类:

package com.design.simplefactory;

public class Apple implements Fruit {
    @Override
    public String fruitName() {
        return "Big Apple";
    }
}      
package com.design.simplefactory;

public class Banana implements Fruit {
    @Override
    public String fruitName() {
        return "Big Banana";
    }
}      

工厂:

package com.design.simplefactory;

public class FruitFactory {

    public static Fruit createFriut(String name){
        switch (name){
            case "apple":
                return new Apple();
            case "banana":
                return new Banana();
            default:
                return null;
        }
    }

    public static void main(String[] args){
        Fruit apple = FruitFactory.createFriut("apple");
        Fruit banana = FruitFactory.createFriut("banana");
        Fruit other = FruitFactory.createFriut("other");
        System.out.println(apple == null?"null":apple.fruitName());
        System.out.println(banana == null?"null":banana.fruitName());
        System.out.println(other == null?"null":other.fruitName());

    }
}      

输出:

Java设计模式--简单工厂模式

小LUA

面对敌人的严刑逼供,我一个字也没说,而是一五一十写了下来。