namespace ConsoleApplication2
{
/* Interpreter
規則のあるフォーマットを解析し処理する。 */
public interface Operand
{
//処理対象を表す文字列を返す
string GetOperandString();
}
//処理対象クラス
public class Ingredient : Operand
{
//処理対象を表す文字列
private string OperandString = "";
public Ingredient(string operandString)
{
this.OperandString = operandString;
}
//処理対象を表す文字列を返す。
public string GetOperandString()
{
return this.OperandString;
}
}
//処理結果クラス
public class Expression : Operand
{
private Operator operate = null;
//処理内容を表すOperatorを引数にとる
public Expression(Operator operate)
{
this.operate = operate;
}
//処理の結果得られるOperandの文字列表現を返す。
public string GetOperandString()
{
return operate.Execute().GetOperandString();
}
}
public interface Operator
{
Operand Execute();
}
//処理の実行
public class Plus : Operator
{
private Operand operand1 = null;
private Operand operand2 = null;
public Plus(Operand operand1, Operand operand2)
{
this.operand1 = operand1;
this.operand2 = operand2;
}
public Operand Execute()
{
return new Ingredient(this.operand1.GetOperandString() + " + " + this.operand2.GetOperandString() + "");
}
}
class Program
{
static void Main(string[] args)
{
Expression expression1 = new Expression(new Plus(new Ingredient("1"),new Ingredient("2")));
System.Console.WriteLine(expression1.GetOperandString());
Expression expression2 = new Expression(new Plus(expression1, new Ingredient("2")));
System.Console.WriteLine(expression2.GetOperandString());
System.Console.ReadKey();
}
}
}