하위 클래스에서 구체적으로 처리.
GUI 앱에서 Menu, Sidebar를 열기/닫기/크기 얻기 동작을 한다고 가정.
/** * 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}; } }
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!"); } }
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!"); } }
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 */