반응형
추상팩토리
- 생산적인 디자인 패턴 중 하나로써 좀 더 factory를 좀 더 생산적으로 만들어 낼 수 있다는 점외에는 factory pattern과 매우 비슷
-인터페이스 보다는 구조체에 접근할 수 있는 코드를 제공한다.
-확장에 매우 용의한 패턴으로 쉽게 다른 서브 클래스들을 확장할 수 있다.
-기존 팩토리 패턴의 if-else 로직에서 벗어날 수 있게 해준다.
package designPattern.abstractFactory;
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;
}
}
package designPattern.abstractFactory;
public class ComputerFactory implements ProductAbstractFactory{
private String name;
private int price;
public ComputerFactory(String name, int price) {
this.name=name;
this.price=price;
}
@Override
public Product createProduct() {
return new Computer(name, price);
}
}
package designPattern.abstractFactory;
public abstract class Product {
public abstract String getName();
public abstract int getPrice();
@Override
public String toString() {
return "product name : " + getName() + ", price :" + getPrice();
}
}
package designPattern.abstractFactory;
public interface ProductAbstractFactory {
public Product createProduct();
}
package designPattern.abstractFactory;
public class ProductFactory {
public static Product getProduct(ProductAbstractFactory product) {
return product.createProduct();
}
public static void main(String[] args) {
Product com = ProductFactory.getProduct(new ComputerFactory("com1", 2000));
Product tk = ProductFactory.getProduct(new TicketFactory("공연", 100000));
System.out.println(com.toString());
System.out.println(tk.toString());
}
}
package designPattern.abstractFactory;
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;
}
}
package designPattern.abstractFactory;
public class TicketFactory implements ProductAbstractFactory {
private String name;
private int price;
public TicketFactory (String name, int price) {
this.name = name;
this.price = price;
}
public Product createProduct() {
return new Ticket(name, price);
}
}
반응형
'Java > Design Pattern' 카테고리의 다른 글
빌더 패턴 Builder (0) | 2023.01.17 |
---|---|
컴포짓 패턴 Composite (0) | 2023.01.16 |
프로토타입 패턴 Prototype (0) | 2023.01.16 |
템플릿 메소드 패턴 (0) | 2023.01.11 |
싱글톤 패턴 Singleton (0) | 2023.01.09 |