温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

设计模式-命令模式

发布时间:2020-07-17 02:27:36 来源:网络 阅读:291 作者:全嗲吉祥 栏目:编程语言
class User
    {
        public string name { get; set; }
        public void Action(string command)
        {
            Console.WriteLine("{0}",command);
        }
    }

abstract class Command
    {
        protected User user;
        public Command(User _user)
        {
            user = _user;
        }
        abstract public void Action();
    }
    class AddCommand : Command
    {
        public AddCommand(User _user) : base(_user)
        {
        }

        public override void Action()
        {
            user.Action("添加一个用户");
        }
    }
    class DeleteCommand : Command
    {
        public DeleteCommand(User _user) : base(_user)
        {
        }

        public override void Action()
        {
            user.Action("删除一个用户");
        }
    }

        class Invoke
    {
        private List<Command> commands = new List<Command>();
        public void AddCommand(Command command)
        {
            commands.Add(command);
        }
        public void RemoveCommand(Command command)
        {
            commands.Remove(command);
        }

        public void Notify()
        {
            foreach (var item in commands)
            {
                item.Action();
            }
        }
    }

        //前端
        static void Main(string[] args)
        {
            User user = new User();
            Demo.Command command = new Demo.AddCommand(user);
            Demo.Command command2 = new Demo.AddCommand(user);
            Demo.Command command3 = new Demo.DeleteCommand(user);
            Invoke i = new Invoke();
            i.AddCommand(command);
            i.AddCommand(command);
            i.AddCommand(command3);
            i.Notify();
            Console.ReadLine();
        }

总结:将请求封装成对象,可以随意扩展请求,并支持请求排队,随意增加请求或者撤销请求。
解耦了请求者与执行者。多了个中间类记录请求者的各种请求,然后一次性传达给执行者。
优点:支持撤销,回滚,支持把请求写入日志。
缺点:命令类会很多。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI