📌 처리에 대한 로직은 정해져 있을때, 이 로직을 구성하는 각각의 세부항목에 대한 처리들을 다르게 정의하고자 할때 사용할 수 있는 패턴
템플릿을(동일한 부분) 작성한다
//Article.java public class Article { private String title; private ArrayList<String> content; private String footer; public Article(String title, ArrayList<String> content, String footer) { this.title = title; this.content = content; this.footer = footer; } public String getTitle() { return title; } public ArrayList<String> getContent() { return content; } public String getFooter() { return this.footer; } } //DisplayArticleTemplate.java public abstract class DisplayArticleTemplate { protected abstract void title(); protected abstract void content(); protected abstract void footer(); protected Article article; public DisplayArticleTemplate(Article article) { this.article = article; } public final void display() { title(); content(); footer(); } }
다르게 동작하는 세부항목 로직을 작성한다
//SimpleArcticle.java public class SimpleArcticle extends DisplayArticleTemplate { public SimpleArcticle(Article article) { super(article); } @Override protected void title() { System.out.println(article.getTitle()); } @Override protected void content() { ArrayList<String> content = article.getContent(); int cntLines = content.size(); for(int i=0; i<cntLines; i++) { System.out.println(content.get(i)); } } @Override protected void footer() { System.out.println(article.getFooter()); } } //CaptionArticle.java public class CaptionArticle extends DisplayArticleTemplate { public CaptionArticle(Article article) { super(article); } @Override protected void title() { System.out.println("TITLE: " + article.getTitle()); } @Override protected void content() { System.out.println("CONTENT:"); ArrayList<String> content = article.getContent(); int cntLines = content.size(); for(int i=0; i<cntLines; i++) { System.out.println(" " + content.get(i)); } } @Override protected void footer() { System.out.println("FOOTER: " + article.getFooter()); } }
하나의 템플릿으로 다르게 동작하는 것을 확인할 수 있다.
//Main.java public class Main { public static void main(String[] args) { String title = "GIS, powerful tool"; ArrayList<String> content = new ArrayList<String>(); content.add("GIS is a geographic information system."); content.add("It is base on real spatial data."); content.add("It provides analyzing spatial and geographic data"); String footer = "2020.10.08, written by Dip2K"; Article article = new Article(title, content, footer); System.out.println("[CASE-1]"); DisplayArticleTemplate style1 = new SimpleArcticle(article); style1.display(); System.out.println(); System.out.println("[CASE-2]"); DisplayArticleTemplate style2 = new CaptionArticle(article); style2.display(); } }