[디자인패턴] Template method 패턴

Template method 패턴

Template method 패턴

Template method 패턴-예제

public abstract class AbstractDisplay {
    public abstract void open();        
    public abstract void print();       
    public abstract void close();      
    public final void display() {       
        open();                             
        for (int i = 0; i < 5; i++) {  
            print();                    
        }
        close();
    }
}

public class CharDisplay extends AbstractDisplay {  
    private char ch;                               
    public CharDisplay(char ch) {            
        this.ch = ch;                               
    }
    @Override
    public void open() {                       
        System.out.print("<<");             
    }
    @Override
    public void print() {                        
        System.out.print(ch);                 
    }
    @Override
    public void close() {                       
        System.out.println(">>");           
    }
}

public class StringDisplay extends AbstractDisplay {   
    private String string;                            
    private int width;                                 
    public StringDisplay(String string) {       
        this.string = string;                           
        this.width = string.getBytes().length;   
    }
    @Override
    public void open() {                                
        printLine();                                    
    }
    @Override
    public void print() {                          
        System.out.println("|" + string + "|");  
    }
    @Override
    public void close() {                               
        printLine();                                    
    }
    private void printLine() {                  
        System.out.print("+");                  
        for (int i = 0; i < width; i++) {      
            System.out.print("-");               
        }
        System.out.println("+");                
    }
}

public class Main {
    public static void main(String[] args) {
        AbstractDisplay d1 = new CharDisplay('H');
        AbstractDisplay d2 = new StringDisplay("Hello, world.");
        AbstractDisplay d3 = new StringDisplay("안녕하세요.");
        d1.display();                                               
        d2.display();                                               
        d3.display();                                               
    }
}