[Design Patterns] Creational Design Patterns - Factory Method
🚀 Factory Method
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 system and handle their creation without affecting client code.
We let sub classes decide which object to instantiate by overriding the factory method.
✓ Implement a Factory Method
✓ Implementation Considerations
✓ Design Considerations
🚫 Pitfalls
🎯 Summary
✓ Code Example
/**
* Description:
* - This class Represents interface for our "product" which is a message
* - Implementations will be specific to content type
*
*/
public abstract class Message {
public abstract String getContent();
public void addDefaultHeaders() {
}
public void encrypt() {
}
}
public class JsonMessage extends Message {
@Override
public String getContent() {
return "{\"Json\":[]}";
}
}
public class TextMessage extends Message {
@Override
public String getContent() {
return "Text";
}
}
/**
* Description:
* - This is our abstract "creator"
* - The abstract method createMessage() has to be implemented by its sub classes
*
*/
public abstract class MessageCreator {
public Message getMessage() {
Message msg = createMessage();
msg.addDefaultHeaders();
msg.encrypt();
return msg;
}
/**
* Description:
* - Factory Method
*
*/
public abstract Message createMessage();
}
/**
* Description:
* - Provides implementation for creating JSON Messages
*
*/
public class JsonMessageCreator extends MessageCreator {
@Override
public Message createMessage() {
return new JsonMessage();
}
}
/**
* Description:
* - Provides implementation for creating Text Messages
*
*/
public class TextMessageCreator extends MessageCreator {
@Override
public Message createMessage() {
return new TextMessage();
}
}
public class Client {
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);
}
}
Reference
この問題について([Design Patterns] Creational Design Patterns - Factory Method), 我々は、より多くの情報をここで見つけました https://velog.io/@dnjscksdn98/Design-Patterns-Creational-Design-Patterns-Factory-Methodテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol