Creational Pattern - Abstract Factory
상세화된 서브클래스를 정의하지 않고도 서로 관련성이 있거나 독립적인 여러 객체의 집합을 생성하기 위한 인터페이스를 제공합니다.(GoF)
기본이 되는 Factory가 재료를 공급하며, 생산된 Product가 정확히 무엇인지 알지 못해도 Product의 인터페이스만 알면 조작할 수 있다.
ProductA
, ProductB
ConcreteProductA1
, ConcreteProductA2
/ ConcreteProductB1
, ConcreteProductB2
createProductA():ProductA
, createProductB():ProductB
createProductA():ConcreteProductA1
, createProductB():ConcreteProductB1
Abstract Factory
, Abstract Products
사용Abstract Products
public interface Monitor {
void turnOn();
}
public interface Keyboard {
void type();
}
public interface Mouse {
void click();
}
Concrete Products
// Monitor
public class SamsungMonitor implements Monitor {
@Override
public void turnOn() {
System.out.println("Samsung 모니터");
}
}
public class LGMonitor implements Monitor {
@Override
public void turnOn() {
System.out.println("LG 모니터");
}
}
public class AppleMonitor implements Monitor {
@Override
public void turnOn() {
System.out.println("Apple 모니터");
}
}
// Keyboard
public class SamsungKeyboard implements Keyboard {
@Override
public void type() {
System.out.println("Samsung 키보드");
}
}
public class LGKeyboard implements Keyboard {
@Override
public void type() {
System.out.println("LG 키보드");
}
}
public class AppleKeyboard implements Keyboard {
@Override
public void type() {
System.out.println("Apple 키보드");
}
}
// Mouse도 동일
Abstract Factory
public interface CompanyFactory {
Monitor createMonitor();
Keyboard createKeyboard();
Mouse createMouse();
}
Concrete Factories
public class SamsungFactory implements CompanyFactory {
@Override
public Monitor createMonitor() {
return new SamsungMonitor();
}
@Override
public Keyboard createKeyboard() {
return new SamsungKeyboard();
}
@Override
public Mouse createMouse() {
return new SamsungMouse();
}
}
public class LGFactory implements CompanyFactory {
@Override
public Monitor createMonitor() {
return new LGMonitor();
}
@Override
public Keyboard createKeyboard() {
return new LGKeyboard();
}
@Override
public Mouse createMouse() {
return new LGMouse();
}
}
public class AppleFactory implements CompanyFactory {
@Override
public Monitor createMonitor() {
return new AppleMonitor();
}
@Override
public Keyboard createKeyboard() {
return new AppleKeyboard();
}
@Override
public Mouse createMouse() {
return new AppleMouse();
}
}
Client
public class Client {
private static final CompanyFactory FACTORY = new Application().createFactory();
public static void main(String[] args) {
Monitor monitor = FACTORY.createMonitor();
monitor.turnOn();
Keyboard keyboard = FACTORY.createKeyboard();
keyboard.type();
Mouse mouse = FACTORY.createMouse();
mouse.click();
}
}
주의
Console
// 입력
APPLE
// 출력
Apple 모니터
Apple 키보드
Apple 마우스
Collection
의 iterator
Factory Method
Abstract Factory
연관이 있는 객체들끼리 묶어 Factory로 만든다.
조건에 따른 1.의 Factory 생성을 다시 Factory를 만들어 위임한다.