1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
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(); } } } |