Interpreter 根据定义的一组合成规则,可以利用解释器模式生成可执行对象

it2022-05-09  26

Command  1using System; 2using System.Collections.Generic; 3using System.Text; 4 5namespace Gof.Test.Interpreter 6{ 7    public abstract class Command 8    { 9        public Command()10        {11            _result = 0;12        }1314        public Command(int result)15        {16            _result = result;17        }1819        public int _result;2021        public abstract void Excute();22    }23} AddOneCommand  1using System; 2using System.Collections.Generic; 3using System.Text; 4 5namespace Gof.Test.Interpreter 6{ 7    public class AddOneCommand : Command 8    { 9        public override void Excute()10        {11            _result += 1;12            Console.WriteLine(_result.ToString());13        }14    }15} AddTwoCommand  1using System; 2using System.Collections.Generic; 3using System.Text; 4 5namespace Gof.Test.Interpreter 6{ 7    public class AddTwoCommand : Command 8    { 9        public override void Excute()10        {11            _result += 2;12            Console.WriteLine(_result.ToString());13        }14    }15} CommandSequence  1using System; 2using System.Collections.Generic; 3using System.Text; 4 5namespace Gof.Test.Interpreter 6{ 7    public class CommandSequence : Command 8    { 9        private IList<Command> list = new List<Command>();1011        public IList<Command> Commands12        {13            get14            {15                return list;16            }17            set18            {19                list = value;20            }21        }2223        public override void Excute()24        {25            foreach (Command c in list)26            {27                c.Excute();28            }29        }30    }31} 客户代码  1            Interpreter.Command addone = new AddOneCommand(); 2            Interpreter.Command addtwo = new AddTwoCommand(); 3            CommandSequence sequence = new CommandSequence(); 4            sequence.Commands.Add(addone); 5            sequence.Commands.Add(addtwo); 6            sequence.Commands.Add(addtwo); 7            sequence.Commands.Add(addone); 8            sequence.Commands.Add(addtwo); 9            sequence.Excute();10            Console.ReadKey();

转载于:https://www.cnblogs.com/nanshouyong326/archive/2007/01/12/619159.html


最新回复(0)