Work & Programming/System Design
[Behavioral Pattern] - Template Method
자전거통학
2024. 5. 16. 10:46
https://refactoring.guru/design-patterns/template-method
Template Method
Problem Imagine that you’re creating a data mining application that analyzes corporate documents. Users feed the app documents in various formats (PDF, DOC, CSV), and it tries to extract meaningful data from these docs in a uniform format. The first vers
refactoring.guru
특정 객체와 그 객체의 메인 로직의 frame이 이미 정해져 있다.
이때 확장을 통해서 해당 구현의 일부/혹은 전체를 변경하고자 할 때 사용.
예시
- document reader : 각 실행 단계가 정해져 있으며 구체화된 객체에서 각기 필요한 추가 기능을 구현한다.
노트
- strategy는 관련 객체의 교체를 통해 로직 변경을 꾀하지만, Template Method는 확장을 통해서 그렇게 한다.
예제 코드
더보기
public abstract class BaseDocReader
{
public virtual void Read()
{
OpenFile();
CheckFormat();
ReadByFormat();
CloseFile();
}
void OpenFile() { }
void CheckFormat() { }
protected abstract void ReadByFormat();
void CloseFile() { }
}
public class MsDocReader : BaseDocReader
{
protected override void ReadByFormat()
{
Console.WriteLine("MsDoc Read");
}
}
public class PdfReader : BaseDocReader
{
protected override void ReadByFormat()
{
Console.WriteLine("Pdf Read");
}
}
internal class TemplateMethodDemo
{
public void Run()
{
BaseDocReader reader = new MsDocReader();
reader.Read();
}
}