Where The Streets Have No Name

template method패턴을 흉내낸 소스입니다. 본문

Developement/Java

template method패턴을 흉내낸 소스입니다.

highheat 2008. 6. 25. 18:45
// Command.java
package ehr.test;

public interface Command {
   
    public void execute();
}

//NonCommand.java
package ehr.test;

public abstract class NonCommand implements Command{
    public abstract void work();
   
    public void execute(){
       
        // 공통코드작성
        System.out.println("NonCommand.execute()");
        work();
        // 공통코드작성
    }
}

//TxCommand.java
package ehr.test;

public abstract class TxCommand implements Command {

    public abstract void work();
   
    public void execute() {
       
        // 공통코드작성
        System.out.println("TxCommand.execute()");
        work();
        // 공통코드작성
    }

}

//ListCommand.java
package ehr.test;

public class ListCommand extends NonCommand {

    public void work() {
        // TODO Auto-generated method stub
        System.out.println("ListCommand.work()");   
    }

}

//AltCommand.java
package ehr.test;

public class AltCommand extends TxCommand {

    public void work() {
        // TODO Auto-generated method stub
        System.out.println("AltCommand.work()");
    }

}

//Template.java
package ehr.test;

public class Template {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Command cmd = null;
        cmd = new ListCommand();
        cmd.execute();
        cmd = new AltCommand();
        cmd.execute();
    }

}


//출력결과
NonCommand.execute()
ListCommand.work()
TxCommand.execute()
AltCommand.work()

위에서 작성한 NonCommand, TxCommand두개의 클래스는 공통된 코드를 모아둔 장소가 됩니다.
반복되는 코드를 옮겨놓으면 좋겠죠