1. 의도
구체적인 서브클래스 정의 없이 관련 객체들을 하나의 군으로 통합시킨 인터페이스를 제공함.
2. 용도
일관된 방식으로 객체를 생성하고자 할 때 유용함.
구체적인 객체 생성을 모두 구체 팩토리 클래스에 위임함으로써, 여러 객체가 생성되는 것을 방지함.
3. UML
4. 구현
public class Client {
public static void main(String[] args) {
ComputerFactory computerFactory = new LGComputerFactory();
computerFactory.createKeyBoard();
computerFactory.createMouse();
}
}
// LGKeyBoard 생성
// LGMouse 생성
================================================================
public interface ComputerFactory {
void createKeyBoard();
void createMouse();
}
================================================================
public class LGComputerFactory implements ComputerFactory {
@Override
public void createKeyBoard() {
new LGKeyBoard();
}
@Override
public void createMouse() {
new LGMouse();
}
}
================================================================
public class SamsungComputerFactory implements ComputerFactory{
@Override
public void createKeyBoard() {
new SamsungKeyBoard();
}
@Override
public void createMouse() {
new SamsungMouse();
}
}
================================================================
public interface KeyBoard {
}
================================================================
public interface Mouse {
}
================================================================
public class LGKeyBoard implements KeyBoard {
public LGKeyBoard() {
System.out.println("LGKeyBoard 생성");
}
}
================================================================
public class SamsungKeyBoard implements KeyBoard {
public SamsungKeyBoard() {
System.out.println("SamsungKeyBoard 생성");
}
}
================================================================
public class LGMouse implements Mouse {
public LGMouse() {
System.out.println("LGMouse 생성");
}
}
================================================================
public class SamsungMouse implements Mouse {
public SamsungMouse() {
System.out.println("SamsungMouse 생성");
}
}
5. 패턴의 장단점
- 장점
- 구체 클래스에서 생성되는 제품들의 상호 호환이 보장됨
- 제품과 클라이언트 코드 사이의 결합이 느슨해짐
- 단일 책임 원칙과 개방/폐쇄 원칙을 준수함
- 단점
- 추상 클래스, 구체 클래스, 추상 팩토리, 구체 팩토리 등 많은 클래스가 필요해 복잡성이 증가함.
- 새로운 제품이 추가될 때마다 추상팩토리와 구체 팩토리 모두 수정해야 함.
출처 :
https://refactoring.guru/design-patterns/abstract-factory
Abstract Factory
Solution The first thing the Abstract Factory pattern suggests is to explicitly declare interfaces for each distinct product of the product family (e.g., chair, sofa or coffee table). Then you can make all variants of products follow those interfaces. For
refactoring.guru
'디자인 패턴' 카테고리의 다른 글
자바(JAVA) - 플라이 웨이트(Flyweight) 패턴 (0) | 2023.11.16 |
---|---|
자바(JAVA) - 팩토리 메서드(Factory Method) 패턴 (0) | 2023.11.15 |
자바(JAVA) - 컴포지트(Composite) 패턴 (0) | 2023.11.02 |
자바(JAVA) - 커맨드(Command) 패턴 (0) | 2023.11.01 |
자바(JAVA) - 데코레이터(Decorator) 패턴 (0) | 2023.10.19 |