Na boa,
Olha só esse primeiro código extraído da Wikipedia:
/* GUIFactory example -- */
interface GUIFactory {
public Button createButton();
}
class WinFactory implements GUIFactory {
public Button createButton() {
return new WinButton();
}
}
class OSXFactory implements GUIFactory {
public Button 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();
}
}
}
Porque gerar FÁBRICAS diferentes para gerar botões diferentes ??
Por que não fazer apenas uma fábrica como no meu código abaixo e então instanciar botões diferentes ??
package abstractfactory;
/* GUIFactory example -- */
interface GUIFactory {
public Button createButton();
}
class WinFactory implements GUIFactory {
public Button createButton() {
return new WinButton();
}
}
class OSXFactory implements GUIFactory {
public Button createButton() {
return new OSXButton();
}
}
class MinhaFactory {
public static Button createButton(int tipo) {
if ( tipo == 0 )
return new WinButton();
else if (tipo == 1)
return new OSXButton();
return null;
}
}
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 AbstractFactory {
public static void main(String[] args) {
Button botao = MinhaFactory.createButton(0); // ou 1
System.out.println(botao.getClass());
botao.paint();
}
}