public interface GuiFactory {
Button createButton();
Checkbox createCheckbox();
}
public interface Button extends Cloneable {
void click();
Button clone();
}
public interface Checkbox extends Cloneable {
void check();
Checkbox clone();
}
public class NixButton implements Button {
@Override
public void click() {
System.out.println("NixButton clicked");
}
@Override
public Button clone() {
return new NixButton();
}
}
public class WinButton implements Button {
@Override
public void click() {
System.out.println("WinButton clicked");
}
@Override
public Button clone() {
return new WinButton();
}
}
public class NixCheckbox implements Checkbox {
@Override
public void check() {
System.out.println("NixCheckbox checked");
}
@Override
public Checkbox clone() {
return new NixCheckbox();
}
}
public class WinCheckbox implements Checkbox {
@Override
public void check() {
System.out.println("WinCheckbox checked");
}
@Override
public Checkbox clone() {
return new WinCheckbox();
}
}
public class NixGuiFactory implements GuiFactory{
@Override
public Button createButton() {
return new NixButton();
}
@Override
public Checkbox createCheckbox() {
return new NixCheckbox();
}
}
public class WinGuiFactory implements GuiFactory {
@Override
public Button createButton() {
return new WinButton();
}
@Override
public Checkbox createCheckbox() {
return new WinCheckbox();
}
}
public enum GuiTypes {
WIN, NIX
}
final public class GuiCreator {
final Button button;
final Checkbox checkbox;
public GuiCreator(GuiFactory factory) {
button = factory.createButton();
checkbox = factory.createCheckbox();
}
public Button getNewButton() {
return button.clone();
}
public Checkbox getNewCheckbox() {
return checkbox.clone();
}
}
public class Application {
public static void main(String args[]) {
GuiTypes guiType = GuiTypes.WIN;
GuiFactory factory = null;
switch (guiType) {
case NIX:
factory = new NixGuiFactory();
break;
case WIN:
factory = new WinGuiFactory();
break;
default:
throw new IllegalStateException();
}
GuiCreator guiCreator = new GuiCreator(factory);
Button button = guiCreator.getNewButton();
Checkbox checkbox = guiCreator.getNewCheckbox();
button.click();
checkbox.check();
}
}
понедельник, 8 августа 2011 г.
Абстрактная фабрика. Пример кода
Подписаться на:
Комментарии к сообщению (Atom)
Комментариев нет:
Отправить комментарий