Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading;
- using System.Linq;
- using System.Threading.Tasks;
- class Program
- {
- static void Main(string[] args)
- {
- Context context = new Context();
- int x = 5,
- y = 8,
- z = 2;
- context.SetVariable("x", 5);
- context.SetVariable("y", 8);
- context.SetVariable("z", 2);
- IExpression expression = new SubstractExpression(
- new AddExpression(
- new NumberExpression("x"), new NumberExpression("y")
- ),
- new NumberExpression("z")
- );
- int result = expression.Interpret(context);
- Console.WriteLine("результат {0}", result);
- Console.ReadLine();
- }
- }
- class Context
- {
- Dictionary<string, int> variables;
- public Context()
- {
- variables = new Dictionary<string, int>();
- }
- public int GetVariables(string name)
- {
- return variables[name];
- }
- public void SetVariable(string name, int value)
- {
- if(variables.ContainsKey(name) == true)
- variables[name] = value;
- else variables.Add(name, value);
- }
- }
- interface IExpression
- {
- int Interpret(Context context);
- }
- class NumberExpression : IExpression
- {
- string name;
- public NumberExpression(string variableName)
- {
- name = variableName;
- }
- public int Interpret(Context context)
- {
- return context.GetVariables(name);
- }
- }
- class AddExpression : IExpression
- {
- IExpression leftExpression;
- IExpression rightExpression;
- public AddExpression(IExpression left, IExpression right)
- {
- leftExpression = left;
- rightExpression = right;
- }
- public int Interpret(Context context)
- {
- return leftExpression.Interpret(context) + rightExpression.Interpret(context);
- }
- }
- class SubstractExpression : IExpression
- {
- IExpression leftExpression;
- IExpression rightExpression;
- public SubstractExpression(IExpression left, IExpression right)
- {
- leftExpression = left;
- rightExpression = right;
- }
- public int Interpret(Context context)
- {
- return leftExpression.Interpret(context) - rightExpression.Interpret(context);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement