时间:2016年05月27日 | 作者 : aaronyang | 分类 : C#开发 | 浏览: 2171次 | 评论 0 人
场景:用于还原上一次存储的对象的状态。
结构图:
这里Ay直接拿 命令的方式去写,我们经常遇到Ctrl+Z撤销命令,还原到上次,为了让模式更好懂,我就简单写了。
第一步:AyCommandManager担当Caretaker角色,AyCommandClonePropery担当Memnto角色,用于存储Originator的值
public class AyCommandManager { private AyCommandClonePropery command; public AyCommandClonePropery Command { get { return command; } set { command = value; } } } public class AyCommandClonePropery { private string commandName; public string CommandName { get { return commandName; } set { commandName = value; } } private Action commandAction; public Action CommandAction { get { return commandAction; } set { commandAction = value; } } }
第二步:新增Originator角色,也就是希望被还原的属性和方法
====================www.ayjs.net 杨洋 wpfui.com ayui ay aaronyang=======请不要转载谢谢了。=========
public class AyCommand { private string commandName; public string CommandName { get { return commandName; } set { commandName = value; } } private Action commandAction; public Action CommandAction { get { return commandAction; } set { commandAction = value; } } public AyCommandClonePropery CreateAyCommand() { AyCommandClonePropery cmd = new AyCommandClonePropery(); cmd.CommandAction = CommandAction; cmd.CommandName = CommandName; return cmd; } public void SetAyCommand(AyCommandClonePropery cmd) { this.CommandName = cmd.CommandName; this.CommandAction = cmd.CommandAction; } public void ExecuteAction() { Console.WriteLine(CommandName+"开始执行:"); CommandAction(); } }
在这里,AyCommandClonePropery是不需要对Client端暴露的,客户端只关注其他的2个类
客户端使用:
AyCommand cmd = new AyCommand(); cmd.CommandName="粘贴"; cmd.CommandAction = () => { Console.WriteLine("执行了粘贴功能"); }; cmd.ExecuteAction();
运行界面:
客户端在不知情的情况下,以为我们没有增加其他功能呢,其实我们增加了备份功能。
//备忘录模式 AyCommand cmd = new AyCommand(); cmd.CommandName="粘贴"; cmd.CommandAction = () => { Console.WriteLine("执行了粘贴功能"); }; cmd.ExecuteAction(); //备份 AyCommandManager cmdManager = new AyCommandManager(); cmdManager.Command = cmd.CreateAyCommand(); cmd.CommandAction = () => { Console.WriteLine("粘贴功能,粘贴失败!"); }; cmd.ExecuteAction(); Console.WriteLine(); Console.WriteLine("还原后,执行上一次的命令"); //还原 cmd.SetAyCommand(cmdManager.Command); cmd.ExecuteAction();
效果图:
总结:通过一个中间类,备份我们给客户提供搞得类的属性,通过给客户提供的2个额外的方法,备份和还原属性,实现备份的效果。
====================www.ayjs.net 杨洋 wpfui.com ayui ay aaronyang=======请不要转载谢谢了。=========
抖音:wpfui 工作wpf
目前在合肥企迈科技公司上班,加我QQ私聊
2023年11月网站停运,将搬到CSDN上
AYUI8全源码 Github地址:前往获取
杨洋(AaronYang简称AY,安徽六安人)和AY交流
高中学历,2010年开始web开发,2015年1月17日开始学习WPF
声明:AYUI7个人与商用免费,源码可购买。部分DEMO不免费
查看捐赠AYUI7.X MVC教程 更新如下:
第一课 第二课 程序加密教程
额 本文暂时没人评论 来添加一个吧
发表评论