码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式-命令模式

时间:2018-05-24 22:22:39      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:设计模式   命令模式   

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(); }

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

设计模式-命令模式

标签:设计模式   命令模式   

原文地址:http://blog.51cto.com/5591787/2120045

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!