//规则:Robert 和 John 是男性 publicstatic Expression getMaleExpression(){ Expression robert = new TerminalExpression("Robert"); Expression john = new TerminalExpression("John"); returnnew OrExpression(robert, john); }
//规则:Julie 是一个已婚的女性 publicstatic Expression getMarriedWomanExpression(){ Expression julie = new TerminalExpression("Julie"); Expression married = new TerminalExpression("Married"); returnnew AndExpression(julie, married); }
System.out.println("John is male? " + isMale.interpret("John")); System.out.println("Julie is a married women? " + isMarriedWoman.interpret("Married Julie")); } }
编译运行以上 Java 范例,输出结果如下
1 2 3 4
$ javac -d . src/main/cn/twle/gof/InterpreterPatternDemo.java $ java cn.twle.gof.InterpreterPatternDemo John is male? true Julie is a married women? true