簡單工廠模式
簡單工廠模式
簡單工廠模式是類的創(chuàng)建模式,又叫靜態(tài)工廠方法模式,它由一個工廠對象決定創(chuàng)建出哪一種產(chǎn)品類的實(shí)例。工廠模式專門負(fù)責(zé)將大量有共同接口的類實(shí)例化,可以動態(tài)決定將哪一個類實(shí)例化,不必事先知道每次要實(shí)例化的是哪一個類
簡單工廠模式的核心是工廠類,它含有必要的判斷邏輯,可以決定在什么時候創(chuàng)建哪一個產(chǎn)品類的實(shí)例。簡單工廠模式一般只有一個工廠方法,如下圖的 Factory 類的 factory() 方法。
例:
?????????????? public ?Factory(){}?
?????????????? public ? static ?art?factory(String?art){?
????????????????????? if (art.equals(“圓形”))?
???????????????????????????? return ? new ?Round();?
????????????????????? else ? if (art.equals(“方形”))?
???????????????????????????? return ? new ?Square();?
????????????????????? else ? if (art.equals(“三角形”))?
???????????????????????????? return ? new ?Triangle();?
?????????????????????else?
??????????????????????????throw new? Exception("不能創(chuàng)建這樣的對象");
}?
}?
??
public ? interface ?Art{?
??????? public ? void ?draw();?
??????? public ? void ?erase();?
}?
??
public ? class ?Round? implements ?Art{?
??????? public ? void ?draw(){?
??????????????System.out.println(“畫一個圓形”);?
}?
public ? void ?erase(){?
???????System.out.println(“刪除一個圓形”);?
}?
}?
??
public ? class ?Square? implements ?Art{?
??????? public ? void ?draw(){?
??????????????System.out.println(“畫一個方形”);?
}?
public ? void ?erase(){?
???????System.out.println(“刪除一個方形”);?
}?
}?
??
public ? class ?Triangle? implements ?Art{?
??????? public ? void ?draw(){?
??????????????System.out.println(“畫一個三角形”);?
}?
public ? void ?erase(){?
???????System.out.println(“刪除一個三角形”);?
}?
}?
??
public ? class ?Main{?
??????? public ? static ? void ?main(String[]?args){?
??????????????Art?art? = ?Factory.factory(“圓形”);?
??????????????art.draw();?
}?
}?
三種角色:
?????????工廠類角色:是簡單工廠方法模式的核心,含有與應(yīng)用緊密聯(lián)系的邏輯。
?????????抽象產(chǎn)品
?????????具體產(chǎn)品
posted on 2009-07-02 22:31 luofeng225 閱讀(219) 評論(0) 編輯 收藏 所屬分類: 設(shè)計模式