Next revision | Previous revision |
design_pattern:template_method_pattern [2017/10/27 10:47] – 만듦 ledyx | design_pattern:template_method_pattern [2021/02/07 03:30] (current) – [Template Method Pattern] ledyx |
---|
* 상위 클래스에서 처리의 뼈대를 세우고, 구체적인 처리를 하위 클래스에서 실행. | * 상위 클래스에서 처리의 뼈대를 세우고, 구체적인 처리를 하위 클래스에서 실행. |
| |
{{tag>Architecture Modeling DesignPattern Behavioral}} | {{tag>Architecture Modeling Design_Pattern Behavioral}} |
| |
| GUI 앱에서 Menu, Sidebar를 열기/닫기/크기 얻기 동작을 한다고 가정. |
| |
| = AbstractClass = |
| <sxh java> |
| /** |
| * Template 역할 |
| */ |
| public abstract class AbstractLayout { |
| private int width; |
| private int height; |
| |
| public AbstractLayout(int width, int height) { |
| this.width = width; |
| this.height = height; |
| } |
| |
| public abstract void open(); |
| public abstract void close(); |
| |
| public final int[] getMesasure() { |
| return new int[] {width, height}; |
| } |
| } |
| </sxh> |
| |
| = ConcreteClass = |
| <sxh java> |
| public class MenuLayout extends AbstractLayout { |
| |
| public MenuLayout(int width, int height) { |
| super(width, height); |
| } |
| |
| @Override |
| public void open() { |
| System.out.println("Menu opened!"); |
| } |
| |
| @Override |
| public void close() { |
| System.out.println("Menu closed!"); |
| } |
| } |
| </sxh> |
| |
| <sxh java> |
| public class SidebarLayout extends AbstractLayout { |
| |
| public SidebarLayout(int width, int height) { |
| super(width, height); |
| } |
| |
| @Override |
| public void open() { |
| System.out.println("Sidebar opened!"); |
| } |
| |
| @Override |
| public void close() { |
| System.out.println("Sidebar closed!"); |
| } |
| } |
| </sxh> |
| |
| = Client = |
| <sxh java> |
| public class Main { |
| public static void main(String[] args) { |
| AbstractLayout menuLayout = new MenuLayout(100, 100); |
| AbstractLayout sidebarLayout = new SidebarLayout(100, 500); |
| |
| print(menuLayout); |
| print(sidebarLayout); |
| } |
| |
| private static void print(AbstractLayout layout) { |
| layout.open(); |
| layout.close(); |
| |
| for(int value : layout.getMesasure()) { |
| System.out.println(value); |
| } |
| |
| System.out.println(); |
| } |
| } |
| |
| /* |
| Menu opened! |
| Menu closed! |
| 100 |
| 100 |
| |
| Sidebar opened! |
| Sidebar closed! |
| 100 |
| 500 |
| */ |
| </sxh> |