Abstract factory - Sam647254/Programetoj GitHub Wiki

Java

interface Button {
  void Point();
}

class WaterButton implements Button {
  @Override
  public void paint() { /* ... */ }
}

class ParkButton implements Button {
  @Override
  public void paint() { /* ... */ }
}

interface GUIFactory {
  public Button createButton();
}

class WaterFactory implements GUIFactory {
  @Override
  public Button createButton() { return new WaterButton(); }
}

class ParkFactory implements GUIFactory {
  @Override
  public Button createButton() { return new ParkButton(); }
}
// main
class Example {
  private static GUIFactory factory(String choice) {
    switch (appearance) {
      case "water":
        return new WaterFactory();
      case "park":
        return new ParkFactory();
    }
  }
  
  public static void main(String[] arguments) {
    var random = List.of("water", "park").get(new Random().nextInt(2));
    var factory = factory(random);
    var button = factory.createButton();
    button.paint();
  }
}

TypeScript

type Choice = "water" | "park";

interface Button {
  paint: () => void;
}

interface GUIFactory {
  createButton: () => Button;
}

function getFactory(Choice choice): GUIFactory {
  switch (choice) {
    case "water":
      return {
        createButton: () => {
          paint: () => { console.log("water"); }
        }
      };
    case "park":
      return {
        createButton: () => {
          paint: () => { console.log("park"); }
        }
      };
  }
}

// main
const choice: Choice = ["water", "park"][Math.round(Math.random())];
const factory = getFactory(choice);
const button = factory.createButton();
button.paint();