java設計模式-工廠模式

工廠模式概念

   之前寫過簡單工廠模式(也稱靜態工廠模式),但是它不屬於23中設計模式之一,並且它也違背了“開閉原則”,因此就有了它的升級版工廠模式,它也是屬於創建型模式,維基百科上對它的定義是這樣的:工廠方法模式的實質是“定義一個創建對象的接口,但讓實現這個接口的類來決定實例化哪個類,工廠方法讓類的實例化推遲到子類中進行。”並且它不像簡單工廠模式那樣,所有對象實例的創建都交給一個大工廠去完成(導致對單一職責的違背),工廠模式是將工廠職責單一化,每個工廠只針對一個對象創建,因此當要新增新的對象時,只需要增加對象類和與之對應的工廠類就可以,不必去修改原有的代碼。


工廠模式類圖

這裏寫圖片描述
衣服的款式有兒童、青年、中年等,它們都有各自的製造工廠來製造它們
說明:
1. InstanceFactory代表創建對象實例工廠接口
2. ChildrenClothesFactory、YouthClothesFactory、MiddleAgeClothesFactory是具體的工廠類,實現InstanceFactory接口
3. Clothes是衣服接口
4. ChildrenClothes、YouthClothes、MiddleAgeClothes是具體款式衣服,現實Clothes接口


工廠模式實現

主體代碼如下:

public interface InstanceFactory {
    public Clothes createInstance();
}
public class ChildrenClothesFactory implements InstanceFactory{
    @Override
    public Clothes createInstance() {
        return new ChildrenClothes();
    }
}
public 
class YouthClothesFactory implements InstanceFactory{
    @Override
    public Clothes createInstance() {
        return new YouthClothes();
    }
}
public class MiddleAgeClothesFactory implements InstanceFactory{
    @Override
    public Clothes createInstance() {
        return new MiddleAgeClothes();
    }
}
public interface Clothes{
    public void applyFor();
}
public class ChildrenClothes implements Clothes{

    @Override
    public void applyFor() {
        System.out.println("兒童穿的衣服");
    }
}
public class YouthClothes implements Clothes{

    @Override
    public void applyFor() {
        System.out.println("青年穿的衣服");
    }
}
public class MiddleAgeClothes implements Clothes{
    @Override
    public void applyFor() {
        System.out.println("中年穿的衣服");
    }
}

測試類代碼:

public class DesignPatternTest {
    @Test
    public void factoryPatternTest(){
        InstanceFactory childrenClothesFactory = new ChildrenClothesFactory();
        Clothes childrenClosthes = childrenClothesFactory.createInstance();
        childrenClosthes.applyFor();

        InstanceFactory youthClothesFactory = new YouthClothesFactory();
        Clothes youthClosthes = youthClothesFactory.createInstance();
        youthClosthes.applyFor();

        InstanceFactory middleAgeClothesFactory = new MiddleAgeClothesFactory();
        Clothes middleAgeClosthes = middleAgeClothesFactory.createInstance();
        middleAgeClosthes.applyFor();
    }

}

輸出如下:
這裏寫圖片描述


工廠模式優缺點

  • 優點:相對簡單工廠來說,遵循了“開閉原則”和“單一職責”。對客戶端隱藏了對象實例化細節,客戶端只需要告訴它們的需求,具體的實例化工作由對應的工廠來執行,和客戶端需求不相干的工廠毫無關係。並且當需要在增加一種老年款式時,只需要增加對應的類和工廠即可,不必修改原有代碼。
  • 缺點:代碼的增加是成對增長的

                                                               -_-沒有天才,只有勤奮的天才
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章