Interpreter

パターンの目的

p.261,line.3: 言語に対して、文法表現と、それを使用して文を解釈するインタプリンタを一緒に定義する。

GoF パターンのクラス図

structure-08-05:interpreter

MixJuice 版 Interpreter (改善)

解決される GoF パターンの問題点

導入可能性の問題点
言語を表すクラス階層が既にあっても、 Interpreter パターンに必要なメソッドが定義されていなければ、後からそのクラス階層を Interpreter パターンとして利用することは難しい。
拡張性の問題点

p.265,line.11-15: 4.表現を解釈する新しい方法を追加する。Interpreterパターンは、表現を新しい方法で評価することを容易にする。たとえば、クラス上に新しいオペレーションを定義することにより、きれいな印刷や型チェックをサポートすることもできる。もし、表現を解釈する新しい方法を継続的に追加していこうとするならば、Visitorパターンを使って文法クラスに変更が及ぶのを避けるようにすることを考える。

対策

AbstractExpression に対するアブストラクトメソッド追加によって解決する

結果

Visitor パターンを使わなくても、新しいオペレーションを追加できる。このとき、すべての ConcreteExpression に対してメソッド実装を追加しなければならない。また、他のモジュールが新しい ConcreteExpresson を導入した場合には補完モジュールが必要になる。

また、抽象構文木があれば、その上に解釈メソッドを追加することにより、パターンを後から導入できる。

構造

structure-08-09:interpreter

module original {
  define class Client {
    AbstractExpression exp;
    Context context;
    define void m(){
      exp.interpret(context);
    }
  }
  define class Context {...}
  define abstract class AbstractExpression {
    define abstract void interpret(Context context);
  }
  define class ExpressionA extends AbstractExpression {
    void interpret(Context context){...}
  }
  define class ExpressionB extends AbstractExpression {
    void interpret(Context context){...}
  }
}
module extension extends original {
  class AbstractExpression {
    define abstract void newOperation();
  }
  class ExpressionA {
    void newOperation(){...}
  }
  class ExpressionB {
    void newOperation(){...}
  }
}

サンプルコード

structure-08-09:interpreter_sample

module expression {
  define abstract class Tree {...}
  define class Node extends Tree {...}
  define class Leaf extends Tree {...}
}

module macro_expantion extends expression {
  class Tree {
    define abstract Tree macroExpand();
  }
  class Node { Tree macroExpand() {...} }
  class Leaf { Tree macroExpand() {...} }
}

module eval extends expression {
  class Tree {
    define abstract Tree eval();
  }
  class Node { Tree eval() {...} }
  class Leaf { Tree eval() {...} }
}

関連するパターン


MixJuice によるデザインパターン改善カタログ


田中 哲 <akr@m17n.org>, 一杉 裕志 <y-ichisugi@aist.go.jp>