Abstract Factory
Abstract Factory Pattern에 대해 설명하는 페이지입니다.
Abstract Factory
Tags
Design Pattern, Java
1. Introduction
- Purpose
- Provide an interface that delegates creation calls to one or more concrete classes in order to deliver specific objects.
- Use When
- The creation of objects should be independent of the system utilizing them.
- Systems should be capable of using multiple families of objects.
- Families of objects must be used together.
- Libraries must be published without exposing implementation details.
- Concrete classes should be decoupled from clients.
- Characteristics
- Delegates object creation to a factory object.
- Uses composition and delegation.
2. Participants
- AbstractFactory
- Declares an interface for operations that create abstract product objects.
- ConcreteFactory
- Implements the operations to create product objects.
- AbstractProduct
- Declares an interface for a type of product object.
- ConcreteProduct
- Defines a product object to be created by the corresponding concrete factory.
- Implements the AbstractProduct interface.
- Client
- Uses only interfaces declared by AbstractFactory and AbstractProduct classes.
3. How to Use (Example)
-
Abstract Factory
java1public interface IngredientFactory { 2 public IngredientA createIngredientA(); 3 public IngredientB createIngredientB(); 4 public IngredientC createIngredientC(); 5} -
Concrete Factory
java1public class MyIngredientFactory implements IngredientFactory { 2 public IngredientA createIngredientA() { 3 return new MyIngredientA(); 4 } 5 6 public IngredientB createIngredientB() { 7 return new MyIngredientB(); 8 } 9 10 public IngredientC createIngredientC() { 11 return new MyIngredientC(); 12 } 13} -
Abstract Product
java1public abstract class Product { 2 IngredientA ingredientA; 3 IngredientB ingredientB; 4 IngredientC ingredientC; 5 6 public abstract void prepare(); 7} -
Concrete Product
java1public class MyProduct extends Product { 2 MyIngredientFactory myIngredientFactory; 3 4 public MyProduct(MyIngredientFactory myIngredientFactory) { 5 this.myIngredientFactory = myIngredientFactory; 6 } 7 8 public void prepare() { 9 ingredientA = myIngredientFactory.createIngredientA(); 10 ingredientB = myIngredientFactory.createIngredientB(); 11 ingredientC = myIngredientFactory.createIngredientC(); 12 } 13}
