Abstract factory

De Viquipèdia
Dreceres ràpides: navegació, cerca

El patró de disseny Abstract factory permet crear diferents famílies d'objectes.

Estructura[modifica | modifica el codi]

El diagrama de classes és el següent:

Diagrama UML

En Lepus3 (llegenda): Model en LePUS3

Codis d'exemple[modifica | modifica el codi]

Java[modifica | modifica el codi]

/* 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();
 }
 }
}

La sortida del programa hauria de ser "I'm a WinButton" o "I'm a OSXButton" depenent del tipus de factoria usat. Tingueu en compte que l'aplicació no té ni idea de quin tipus de GUIFactory es dóna, o fins i tot quin tipus de botó que genera la fàbrica.

C++[modifica | modifica el codi]

/* a GUIFactory exemple en C++ */

struct GUIFactory{
 virtual Button* createButton () = 0;
};

struct WinGUIFactory : public GUIFactory{
 Button* createButton (){
 return new WinButton();
 }
};

struct OSXGUIFactory : public GUIFactory{
 Button* createButton (){
 return new OSXButton();
 }
};

struct Button{
 virtual void paint() = 0;
};

struct WinButton : public Button{
 void paint (){
 std::cout << " I'm a window button \n";
 }
};

struct OSXButton : public Button{
 void paint (){
 std::cout << " I'm a OSX button \n";
 }
};

struct Application {
 Application(GUIFactory* factory){
 Button * button = factory->createButton();
 button->paint();
 }
};

/* application code */

int main()
{
 GUIFactory* factory1 = new WinFactory();
 GUIFactory* factory2 = new OSXFactory();

 Application* winApp = new Application (factory1); 
 Application* osxApp = new Application (factory2);

 delete factory1, factory2;

 return 0;
}


Enllaços externs[modifica | modifica el codi]