Factory Method

직접 객체λ₯Ό μƒμ„±ν•˜μ§€ μ•Šκ³  νŒ©ν† λ¦¬ λ©”μ„œλ“œ ν΄λž˜μŠ€μ—μ„œ 객체λ₯Ό λŒ€μ‹  μƒμ„±μ‹œν‚¨λ‹€.

public abstract class Product {
  public abstract String getName();
  public abstract int getPrice();
}
public class Computer extends Product {
  private String name;
  private int price;

  public Computer (String name, int price) {
      this.name = name;
      this.price = price;
  }

  @Override
  public String getName() {
      return this.name;
  }

  @Override
  public int getPrice() {
      return this.price;
  }
}
public class Ticket extends Product {
  private String name;
  private int price;

  public Ticket (String name, int price) {
      this.name = name;
      this.price = price;
  }

  @Override
  public String getName() {
      return this.name;
  }
  @Override
  public int getPrice () {
      return this.price;
  }
}
public class ProductFactory {
  public static Product getInstance(String, type, String name, int price) {
    if ("computer".equals(type)) {
      return new Computer(name, price);
    } else if ("ticket".equals(type)) {
      return new Ticket(name, price);
    }
  }
}
public class FactoryTestCode {
  public static void main(String[] args) {
    Product p1 = ProductFactory.getInstance("computer", "pc", 500);
    Product p2 = ProductFactory.getInstance("ticket", "μ—¬ν–‰", 300)
  }
}

μž₯점

μœ μ§€λ³΄μˆ˜κ°€ μš©μ΄ν•˜λ‹€.