1. 程式人生 > 實用技巧 >設計模式-直譯器模式

設計模式-直譯器模式

直譯器模式

1. 模式的結構

直譯器模式包含以下主要角色。

  1. 抽象表示式(Abstract Expression)角色:定義直譯器的介面,約定直譯器的解釋操作,主要包含解釋方法 interpret()。
  2. 終結符表示式(Terminal Expression)角色:是抽象表示式的子類,用來實現文法中與終結符相關的操作,文法中的每一個終結符都有一個具體終結表示式與之相對應。
  3. 非終結符表示式(Nonterminal Expression)角色:也是抽象表示式的子類,用來實現文法中與非終結符相關的操作,文法中的每條規則都對應於一個非終結符表示式。
  4. 環境(Context)角色:通常包含各個直譯器需要的資料或是公共的功能,一般用來傳遞被所有直譯器共享的資料,後面的直譯器可以從這裡獲取這些值。
  5. 客戶端(Client):主要任務是將需要分析的句子或表示式轉換成使用直譯器物件描述的抽象語法樹,然後呼叫直譯器的解釋方法,當然也可以通過環境角色間接訪問直譯器的解釋方法。
//抽象表示式類
interface AbstractExpression
{
    public Object interpret(String info);    //解釋方法
}
//終結符表示式類
class TerminalExpression implements AbstractExpression
{
    public Object interpret(String info)
    {
        //對終結符表示式的處理
    }
}
//非終結符表示式類
class NonterminalExpression implements AbstractExpression
{
    private AbstractExpression exp1;
    private AbstractExpression exp2;
    public Object interpret(String info)
    {
        //非對終結符表示式的處理
    }
}
//環境類
class Context
{
    private AbstractExpression exp;
    public Context()
    {
        //資料初始化
    }
    public void operation(String info)
    {
        //呼叫相關表示式類的解釋方法
    }
}
package interpreterPattern;
import java.util.*;
/*文法規則
  <expression> ::= <city>的<person>
  <city> ::= 韶關|廣州
  <person> ::= 老人|婦女|兒童
*/
public class InterpreterPatternDemo
{
    public static void main(String[] args)
    {
        Context bus=new Context();
        bus.freeRide("韶關的老人");
        bus.freeRide("韶關的年輕人");
        bus.freeRide("廣州的婦女");
        bus.freeRide("廣州的兒童");
        bus.freeRide("山東的兒童");
    }
}
//抽象表示式類
interface Expression
{
    public boolean interpret(String info);
}
//終結符表示式類
class TerminalExpression implements Expression
{
    private Set<String> set= new HashSet<String>();
    public TerminalExpression(String[] data)
    {
        for(int i=0;i<data.length;i++)set.add(data[i]);
    }
    public boolean interpret(String info)
    {
        if(set.contains(info))
        {
            return true;
        }
        return false;
    }
}
//非終結符表示式類
class AndExpression implements Expression
{
    private Expression city=null;    
    private Expression person=null;
    public AndExpression(Expression city,Expression person)
    {
        this.city=city;
        this.person=person;
    }
    public boolean interpret(String info)
    {
        String s[]=info.split("的");       
        return city.interpret(s[0])&&person.interpret(s[1]);
    }
}
//環境類
class Context
{
    private String[] citys={"韶關","廣州"};
    private String[] persons={"老人","婦女","兒童"};
    private Expression cityPerson;
    public Context()
    {
        Expression city=new TerminalExpression(citys);
        Expression person=new TerminalExpression(persons);
        cityPerson=new AndExpression(city,person);
    }
    public void freeRide(String info)
    {
        boolean ok=cityPerson.interpret(info);
        if(ok) System.out.println("您是"+info+",您本次乘車免費!");
        else System.out.println(info+",您不是免費人員,本次乘車扣費2元!");   
    }
}