언어로 문제를 해결하기
Class Diagram
Sample Code
public interface AbstractExpression {
public void interprete(Context context);
}
public class TerminalExpression implements AbstractExpression {
@Override
public void interprete(Context context) {
String token = context.currentToken();
if (!"go".equals(token) ) {
new NonTerminalExpression().interprete(context);
} else {
System.out.println("go");
}
}
}
public class NonTerminalExpression implements AbstractExpression {
@Override
public void interprete(Context context) {
String token = context.currentToken();
if ( "begin".equals(token)) {
System.out.println("begin");
while ((token = context.nextToken()) != null )
{
new TerminalExpression().interprete(context);
}
} else if ( "end".equals(token)) {
System.out.println("end");
} else {
System.out.println("error");
}
}
}
public class Context {
private StringTokenizer tokenizer;
private String currentToken;
public Context(String text) {
tokenizer = new StringTokenizer(text);
this.nextToken();
}
public String nextToken() {
if (tokenizer.hasMoreTokens()) {
currentToken = tokenizer.nextToken();
} else {
currentToken = null;
}
return currentToken;
}
public String currentToken() {
return currentToken;
}
}
public class Client {
public static void main(String[] args) {
String text = "begin go go go end";
Context context = new Context(text);
NonTerminalExpression nonTerminalExpression = new NonTerminalExpression();
nonTerminalExpression.interprete(context);
}
}
Caution
특별한 주의사항은 없다.
'Methdology > Design Pattern' 카테고리의 다른 글
Command - 명령을 클래스로 표현하기 (0) | 2012.04.30 |
---|---|
State - 클래스로 상태 표현하기 (0) | 2012.04.27 |
Memento - 상태 저장하기 (0) | 2012.04.26 |
Observer - 자신의 상태를 전달하기 (2) | 2012.04.26 |
Mediator - 중개인을 통해 지시내리기 (1) | 2012.04.26 |