Factory Method Pattern
Factory Method Pattern에 대해 설명하는 페이지입니다.
Factory Method Pattern
Tags
Design Pattern, Java
1. Introduction
- Purpose
- Exposes a method for creating objects, allowing subclasses to control the actual creation process.
- Use When
- A class will not know what classes it will be required to create.
- Subclasses may specify what objects should be created.
- Parent classes wish to defer creation to their subclasses.
- Characteristics
- Uses inheritance to decide the object to be instantiated.
- Defines an interface for creating an object, but lets subclasses decide which class to instantiate.
- Lets a class defer instantiation to subclasses.
2. How to Use (Example)
-
Product
java1public abstract class MyProduct { 2 String name; 3 4 public String getName() { 5 return name; 6 } 7} -
Concrete Products
java1public class ProductA extends MyProduct { 2 public ProductA() { 3 name = "ProductA"; 4 } 5} 6 7public class ProductB extends MyProduct { 8 public ProductB() { 9 name = "ProductB"; 10 } 11} 12 13public class ProductC extends MyProduct { 14 public ProductC() { 15 name = "ProductC"; 16 } 17} 18 19public class ProductD extends MyProduct { 20 public ProductD() { 21 name = "ProductD"; 22 } 23} -
Creator
java1public abstract class MyCreator { 2 public MyProduct orderProduct(String type) { 3 Product product = createProduct(type); 4 return product; 5 } 6 7 protected abstract MyProduct createProduct(String type); 8} -
Concrete Creators
java1public class CreatorAB extends MyCreator { 2 public MyProduct createProduct(String type) { 3 Product product; 4 if (type.equals("A")) { 5 product = new ProductA(); 6 } else if (type.equals("B")) { 7 product = new ProductB(); 8 } 9 return product; 10 } 11} 12 13public class CreatorCD extends MyCreator { 14 public MyProduct createProduct(String type) { 15 Product product; 16 if (type.equals("C")) { 17 product = new ProductC(); 18 } else if (type.equals("D")) { 19 product = new ProductD(); 20 } 21 return product; 22 } 23}
