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)
}
}
μ₯μ
μ μ§λ³΄μκ° μ©μ΄νλ€.
β Strategy Template Method β