溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

設(shè)計模式-命令模式

發(fā)布時間:2020-07-17 02:27:36 來源:網(wǎng)絡(luò) 閱讀:289 作者:全嗲吉祥 欄目:編程語言
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();
        }

總結(jié):將請求封裝成對象,可以隨意擴(kuò)展請求,并支持請求排隊,隨意增加請求或者撤銷請求。
解耦了請求者與執(zhí)行者。多了個中間類記錄請求者的各種請求,然后一次性傳達(dá)給執(zhí)行者。
優(yōu)點(diǎn):支持撤銷,回滾,支持把請求寫入日志。
缺點(diǎn):命令類會很多。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI