욱'S 노트

Intepreter - 언어로 문제를 해결하기 본문

Methdology/Design Pattern

Intepreter - 언어로 문제를 해결하기

devsun 2012. 4. 30. 13:20
When Using It

언어로 문제를 해결하기

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


특별한 주의사항은 없다. 
Comments