-
Factory PatternModeling/DesignPattern 2019. 8. 22. 09:17
1. Overview
The factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.
2. Description
2.1 Motivation
- We want to move the object creation logic from our code to a separate class.
- We use this pattern when we do not know in advance which class we may need to instantiate beforehand. Also to allow new classes to be added to the system and handle their creation without affecting client code.
- We let subclasses decide which object to instantiate by overriding the factory method
2.2 Consideration
2.2.1 Implementation
- The creator can be either concrete or abstract which provides a default implementation for the factory method. In concrete cases, you'll create some default object in base creator.
- You can pass additional arguments to choose between different object types. Subclasses can then override the factory methods to selectively create different objects for some criteria.
2.2 Design
- Creator hierarchy in the factory method pattern reflects the product hierarchy. We typically end up with a concrete creator per object type.
- Template method design pattern often makes use of factory methods
- Another creational design pattern called the abstract factory makes use of a factory method pattern.
3. Example
abstract class Message { public abstract String getContent(); public void addDefaultHeaders() { } public void encrypt() { } } class JSONMessage extends Message { @Override public String getContent() { return "{\"JSON\":[]}"; } } class TextMessage extends Message { @Override public String getContent() { return "Text message"; } } abstract class MessageCreator { public Message getMessage() { // Invoking Factory method Message msg = createMessage(); msg.addDefaultHeaders(); msg.encrypt(); return msg; } // Factory method public abstract Message createMessage(); } class JSONMessageCreator extends MessageCreator { @Override public Message createMessage() { return new TextMessage(); } } class TextMessageCreator extends MessageCreator { @Override public Message createMessage() { return new TextMessage(); } } public class DemoClient { public static void main(String[] args) { printMessage(new JSONMessageCreator()); printMessage(new TextMessageCreator()); } public static void printMessage(MessageCreator creator) { Message msg = creator.getMessage(); System.out.println(msg); } }
4. Reference
'Modeling > DesignPattern' 카테고리의 다른 글
Model–view–controller (MVC) (0) 2020.02.23 Categorizing Design Pattern (0) 2019.09.29 Abstract factory (0) 2019.08.23 Simple Factory Pattern (0) 2019.08.22 Bridge Design Pattern (0) 2019.08.19