我使用作爲http://en.wikipedia.org/wiki/Abstract_factory這是一個有效的抽象工廠設計模式嗎?
定義的抽象工廠模式的變體的模式編碼在維基百科上,像這樣 -
/* GUIFactory example -- */
interface GUIFactory {
public Button createButton();
}
class WinFactory implements GUIFactory {
public WinButton createButton() {
return new WinButton();
}
}
class OSXFactory implements GUIFactory {
public OSXButton createButton() {
return new OSXButton();
}
}
interface Button {
public void paint();
}
class WinButton implements Button {
public void paint() {
System.out.println("I'm a WinButton");
}
}
class OSXButton implements Button {
public void paint() {
System.out.println("I'm an OSXButton");
}
}
class Application {
public Application(GUIFactory factory) {
Button button = factory.createButton();
button.paint();
}
}
public class ApplicationRunner {
public static void main(String[] args) {
new Application(createOsSpecificFactory());
}
public static GUIFactory createOsSpecificFactory() {
int sys = readFromConfigFile("OS_TYPE");
if (sys == 0) {
return new WinFactory();
} else {
return new OSXFactory();
}
}
}
我在我dont't使用它略有不同需要進一步的抽象層來重寫Button實現中的繪畫行爲。
我的代碼 -
//Implmentation code
MainMenuButtonFactory mainMenuButtonFactory = new SyncButtonFactory();
BitmapButtonField refreshButton = mainMenuButtonFactory.createButton();
public interface MainMenuButtonFactory {
BitmapButtonField createButton();
}
public class SyncButtonFactory implements MainMenuButtonFactory{
public BitmapButtonField createButton() {
return new BitmapButtonField(ButtonImageFactory.getResyncBitmap(),
ButtonImageFactory.getResyncBitmapHighlight()){
public boolean navigationClick(int status, int time)
{
FutureContent.future.clearContent();
ScreenController.displayNextScreen(new UpdatingScreenAnimation(Constants.MAIN_MENU_SCREEN));
return super.navigationClick(status, time);
}
};
}
}
public class JudgeButtonFactory implements MainMenuButtonFactory{
public BitmapButtonField createButton() {
BitmapButtonField judgeButton = new BitmapButtonField(ButtonImageFactory.getJudgeBitmap(),
ButtonImageFactory.getJudgeBitmapHighlight()){
public boolean navigationClick(int status, int time)
{
RatingsScreenController ratingsScreenController = new RatingsScreenController("MainMenuScreen");
Thread t = new Thread(ratingsScreenController);
t.start();
return super.navigationClick(status, time);
}
};
return judgeButton;
}
}
仍然是這個有效的抽象工廠設計模式?
是的,我有MainMenuButtonFactory的多個實現,但這些實現只是從一個類中調用。 –
抽象工廠的顯着特點是方法產生兼容對象。在你的例子中:Windows風格的按鈕帶有Windows風格的組合框。並且使用這種模式,您不會錯誤 –