天天看點

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

面對敵人的嚴刑逼供,我一個字也沒說,而是一五一十寫了下來。