static void Main(string[] args) { // 苹果手机 Phone phone = new ApplePhone(); // 苹果手机贴膜 Decorator applePhoneWithSticker = new Sticker(phone); // 扩展贴膜行为 applePhoneWithSticker.Print(); Console.WriteLine("————————————"); // 苹果手机挂件 Decorator applePhoneWithAccessories = new Accessories(phone); // 扩展手机挂件行为 applePhoneWithAccessories.Print(); Console.WriteLine("————————————"); // 同时贴膜和手机挂件 Sticker sticker = new Sticker(phone); Accessories applePhoneWithAccessoriesAndSticker = new Accessories(sticker); applePhoneWithAccessoriesAndSticker.Print(); Console.ReadLine(); }
static void Main(string[] args) { try { { AndroidPhone phone = new AndroidPhone(); phone.Call(); } { IPhone phone = new ApplePhone(); phone.Call(); } { IPhone phone = ObjectFactory.CreateInstance(); phone.Call(); } { //IocTest.Show(); } { } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); }
/// <summary> /// 装饰者模式 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button9_Click(object sender, EventArgs e) { // 我买了个苹果手机 Phone phone = new ApplePhone(); // 现在想贴膜了 Decorator applePhoneWithSticker = new Sticker(phone); // 扩展贴膜行为 applePhoneWithSticker.Print(); Console.WriteLine("----------------------\n"); // 现在我想有挂件了 Decorator applePhoneWithAccessories = new Accessories(phone); // 扩展手机挂件行为 applePhoneWithAccessories.Print(); Console.WriteLine("----------------------\n"); // 现在我同时有贴膜和手机挂件了 Sticker sticker = new Sticker(phone); Accessories applePhoneWithAccessoriesAndSticker = new Accessories(sticker); applePhoneWithAccessoriesAndSticker.Print(); Console.ReadLine(); }
/// <summary> /// 以手机和手机配件的例子来演示装饰者模式的实现 /// </summary> public void DecoratorPhone() { //我买了个苹果手机 Phone phone = new ApplePhone(); // 现在想贴膜了 (开始装饰了) Decorator applePhoneWithSticker = new PhoneSticker(phone); //想让手机贴膜,得给贴膜人,所以要把苹果手机传给贴膜人 //扩展贴膜行为 applePhoneWithSticker.Print(); Console.WriteLine("----------------------\n"); // 现在我想有挂件了 Decorator applePhoneAccesstories = new PhoneAccessories(phone); applePhoneAccesstories.Print(); Console.WriteLine("----------------------\n"); // 现在我同时有贴膜和手机挂件了 PhoneSticker sticker = new PhoneSticker(phone); PhoneAccessories accessory = new PhoneAccessories(sticker); accessory.Print(); Console.WriteLine("----------------------\n"); // 现在我同时有贴膜和手机挂件了 另一组合方法 Decorator sticker2 = new PhoneSticker(phone); Decorator accessory2 = new PhoneAccessories(sticker2); accessory2.Print(); }
static void RegisterType() { Console.WriteLine("RegisterType:开始注册"); var orzAutofac = LazySingleton <OrzAutofac> .Instance; orzAutofac.RegisterType <IHeadphone, Headphone>(); orzAutofac.RegisterType <IMicrophone, Microphone>(); orzAutofac.RegisterType <IPower, Power>(); orzAutofac.Register <IPhone, ApplePhone>(n => { var apple = new ApplePhone(n.Resolve <IMicrophone>()) { Headphone = n.Resolve <IHeadphone>() }; apple.Init(n.Resolve <IPower>()); return(apple); }); orzAutofac.BuildContainer(); Console.WriteLine("第一次获取对象:"); Print(); Console.WriteLine("第二次获取对象:"); Print(); }
// GET: ApplePhone public ActionResult Index() { ApplePhone strHome = new ApplePhone(); List <ApplePhone> obj = strHome.GetHome(); return(View(obj)); }
public void Main() { ILightningPhone applePhone = new ApplePhone(); IUsbPhone adapterCable = new LightningToUsbAdapter(applePhone); adapterCable.ConnectUsb(); adapterCable.Recharge(); }
public void DecoratorTest() { { var m = new ConcreteComponent(); var decoratorA = new DecoratorA(m); // decoratorA.Work(); var decoratorB = new DecoratorB(decoratorA); decoratorB.Work(); } { // 我买了个苹果手机 Phone phone = new ApplePhone(); // 现在想贴膜了 var applePhoneWithSticker = new Sticker(phone); // 扩展贴膜行为 applePhoneWithSticker.Print(); // 现在我想有挂件了 var applePhoneWithAccessories = new Accessories(phone); // 扩展手机挂件行为 applePhoneWithAccessories.Print(); Console.WriteLine("----------------------"); // 现在我同时有贴膜和手机挂件了 var sticker = new Sticker(phone); var applePhoneWithAccessoriesAndSticker = new Accessories(sticker); applePhoneWithAccessoriesAndSticker.Print(); } // { // AbstractMessage message = new SqlMessage(); // var de = new CheckUserWrapper(message); // Console.WriteLine(de.Get()[0].Message); // // var d2 = new CheckInputWrapper(message); // Console.WriteLine(d2.Get()[0].Message); // // var m3 = new CheckUserWrapper(message); // var m4 = new CheckInputWrapper(m3); // Console.WriteLine(m4.Get()[0].Message); // } { var dark = new DarkRoast("黑咖啡"); var sugar = new Sugar("加糖", dark); Console.WriteLine($"{sugar.GetDescription()}{sugar.Cost()}元");; var milk = new Milk("加奶", sugar); Console.WriteLine($"{milk.GetDescription()}{milk.Cost()}元");; } }
static void Main(string[] args) { Beverage beverage = new Espresso(); Console.WriteLine(beverage.GetDescription() + " $" + beverage.Cost()); Beverage beverage2 = new HouseBlend(); beverage2 = new Mocha(beverage2); beverage2 = new Soy(beverage2); beverage2 = new Whip(beverage2); Console.WriteLine(beverage2.GetDescription() + " $" + beverage2.Cost()); Beverage beverage3 = new DarkRoase(); beverage3 = new Mocha(beverage3); beverage3 = new Mocha(beverage3); beverage3 = new Whip(beverage3); Console.WriteLine(beverage3.GetDescription() + " $" + beverage3.Cost()); //Console.ReadLine(); Console.WriteLine("---------------------\n"); // 我买了个苹果手机 Phone phone = new ApplePhone(); // 现在想贴膜了 Decorator applePhoneWithSticker = new Sticker(phone); // 扩展贴膜行为 applePhoneWithSticker.Print(); Console.WriteLine("----------------------\n"); // 现在我想有挂件了 Decorator applePhoneWithAccessories = new Accessories(phone); // 扩展手机挂件行为 applePhoneWithAccessories.Print(); Console.WriteLine("----------------------\n"); // 现在我同时有贴膜和手机挂件了 Sticker sticker = new Sticker(phone); Accessories applePhoneWithAccessoriesAndSticker = new Accessories(sticker); applePhoneWithAccessoriesAndSticker.Print(); Console.ReadLine(); }
static void Main(string[] args) { try { Console.WriteLine("****************************************"); { Abstract.AbstractPhone phone = new ApplePhone(); phone.System(); phone.Call(); } { Abstract.AbstractPhone phone = new P10(); phone.System(); phone.Call(); dynamic dyn_phone = phone; dyn_phone.System(); dyn_phone.Movie(); dyn_phone.Price = 19; Console.WriteLine("Price:{0}", dyn_phone.Price); } Console.WriteLine(); Console.WriteLine("****************************************"); { IExtend extend = new ApplePhone(); extend.Movie(); extend.Price = 19; Console.WriteLine("Price:{0}", extend.Price); } { } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); }
public static void Show() { Console.WriteLine("**************************************"); { ApplePhone applePhone = new ApplePhone(); Console.WriteLine("applePhone.iHeadphone==null? {0}", applePhone.iHeadphone == null); Console.WriteLine("applePhone.iMicrophone==null? {0}", applePhone.iMicrophone == null); Console.WriteLine("applePhone.iPower==null? {0}", applePhone.iPower == null); } Console.WriteLine("*****************UnityAndroid*********************"); { IUnityContainer container = new UnityContainer(); container.RegisterType <IPhone, AndroidPhone>(); //接口--类型 父类-子类 抽象类-子类 //container.RegisterInstance<IPhone>(new AndroidPhone());//实例注册 IPhone phone = container.Resolve <IPhone>(); Console.WriteLine("phone.iHeadphone==null? {0}", phone.iHeadphone == null); Console.WriteLine("phone.iMicrophone==null? {0}", phone.iMicrophone == null); Console.WriteLine("phone.iPower==null? {0}", phone.iPower == null); } Console.WriteLine("*****************UnityApple*********************"); { IUnityContainer container = new UnityContainer(); container.RegisterType <IPhone, ApplePhone>(); container.RegisterType <IMicrophone, Microphone>(); container.RegisterType <IHeadphone, Headphone>(); container.RegisterType <IPower, Power>(); IPhone phone = container.Resolve <IPhone>(); Console.WriteLine("phone.iHeadphone==null? {0}", phone.iHeadphone == null); Console.WriteLine("phone.iMicrophone==null? {0}", phone.iMicrophone == null); Console.WriteLine("phone.iPower==null? {0}", phone.iPower == null); } Console.WriteLine("*****************UnityContainer*********************"); { IUnityContainer container = new UnityContainer(); container.RegisterType <IPhone, ApplePhone>(new PerResolveLifetimeManager()); container.RegisterType <IPhone, ApplePhone>("Apple"); container.RegisterType <IPhone, AndroidPhone>("Android"); container.RegisterType <IMicrophone, Microphone>(); container.RegisterType <IHeadphone, Headphone>(); container.RegisterType <IPower, Power>(); container.AddNewExtension <Interception>().Configure <Interception>() .SetInterceptorFor <IPhone>(new InterfaceInterceptor()); IPhone iphone1 = container.Resolve <IPhone>(); iphone1.Call(); IPhone iphone2 = container.Resolve <IPhone>("Apple"); IPhone iphone3 = container.Resolve <IPhone>("Android"); IPhone iphone4 = container.Resolve <IPhone>(); IPhone iphone5 = container.Resolve <IPhone>(); } Console.WriteLine("*****************UnityContainer*********************"); { IUnityContainer container = new UnityContainer(); //container.RegisterType<IPhone, AndroidPhone>(new TransientLifetimeManager());瞬时 container.RegisterType <IPhone, AndroidPhone>(new ContainerControlledLifetimeManager());//容器单例 //container.RegisterType<IPhone, AndroidPhone>(new PerThreadLifetimeManager());//线程单例 IPhone iphone1 = null; Action act1 = new Action(() => { iphone1 = container.Resolve <IPhone>(); }); var result1 = act1.BeginInvoke(null, null); IPhone iphone2 = null; Action act2 = new Action(() => { iphone2 = container.Resolve <IPhone>(); }); var result2 = act2.BeginInvoke(null, null); act1.EndInvoke(result1); act2.EndInvoke(result2); //IPhone iphone1 = container.Resolve<IPhone>(); //IPhone iphone2 = container.Resolve<IPhone>(); Console.WriteLine(object.ReferenceEquals(iphone1, iphone2)); } Console.WriteLine("*****************UnityContainer*********************"); { ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\\Unity.Config.xml");//找配置文件的路径 Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName); IUnityContainer container = new UnityContainer(); section.Configure(container, "testContainer"); IPhone phone = container.Resolve <IPhone>(); phone.Call(); } Console.WriteLine("*****************UnityContainer*********************"); { ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\\Unity.Config.xml");//找配置文件的路径 Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName); IUnityContainer container = new UnityContainer(); section.Configure(container, "testContainerAOP"); IPhone phone = container.Resolve <IPhone>(); phone.Call(); } }
public static void Show() { Console.WriteLine("**************************************"); { ApplePhone applePhone = new ApplePhone(); Console.WriteLine("applePhone.Headphone==null? {0}", applePhone.Headphone == null); Console.WriteLine("applePhone.Microphone==null? {0}", applePhone.Microphone == null); Console.WriteLine("applePhone.Bluetooth==null? {0}", applePhone.Bluetooth == null); } Console.WriteLine("*****************UnityAndroid*********************"); { IUnityContainer container = new UnityContainer(); container.RegisterType <IPhone, AndroidPhone>(); //接口--类型 父类-子类 抽象类-子类 ////container.RegisterInstance<IPhone>(new AndroidPhone());//实例注册 IPhone phone = container.Resolve <IPhone>(); //phone.Call(); Console.WriteLine("applePhone.Headphone==null? {0}", phone.Headphone == null); Console.WriteLine("applePhone.Microphone==null? {0}", phone.Microphone == null); Console.WriteLine("applePhone.Bluetooth==null? {0}", phone.Bluetooth == null); } Console.WriteLine("*****************UnityApple*********************"); { IUnityContainer container = new UnityContainer(); container.RegisterType <IPhone, ApplePhone>(); container.RegisterType <IMicrophone, Microphone>(); container.RegisterType <IHeadphone, Headphone>(); container.RegisterType <IBluetooth, Bluetooth>(); IPhone phone = container.Resolve <IPhone>(); Console.WriteLine("applePhone.Headphone==null? {0}", phone.Headphone == null); Console.WriteLine("applePhone.Microphone==null? {0}", phone.Microphone == null); Console.WriteLine("applePhone.Bluetooth==null? {0}", phone.Bluetooth == null); } { Console.WriteLine("*****************UnityContainer*********************"); IUnityContainer container = new UnityContainer(); // container.RegisterType<IPhone, AndroidPhone>(new TransientLifetimeManager());//瞬态生命周期 //container.RegisterType<IPhone, AndroidPhone>(new ContainerControlledLifetimeManager());//容器单例 container.RegisterType <IPhone, AndroidPhone>(new PerThreadLifetimeManager()); //IPhone iphone1 = null; //Action act1 = new Action(() => //{ // iphone1 = container.Resolve<IPhone>(); //}); //IAsyncResult result1 = act1.BeginInvoke(null, null); //IPhone iphone2 = null; //Action act2 = new Action(() => //{ // iphone2 = container.Resolve<IPhone>(); //}); //IAsyncResult result2 = act2.BeginInvoke(null, null); //act1.EndInvoke(result1); //act2.EndInvoke(result2); IPhone iphone1 = container.Resolve <IPhone>(); IPhone iphone2 = container.Resolve <IPhone>(); Console.WriteLine(object.ReferenceEquals(iphone1, iphone2)); } Console.WriteLine("*****************UnityContainer*********************"); { ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\\Unity.Config.xml");//找到配置文件路径 Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection(Microsoft.Practices.Unity.Configuration.UnityConfigurationSection.SectionName); IUnityContainer container = new UnityContainer(); section.Configure(container, "configContainer"); IPhone phone = container.Resolve <IPhone>(); Console.WriteLine("applePhone.Headphone==null? {0}", phone.Headphone == null); Console.WriteLine("applePhone.Microphone==null? {0}", phone.Microphone == null); Console.WriteLine("applePhone.Bluetooth==null? {0}", phone.Bluetooth == null); phone.Call(); } }
public static void Main(string[] args) { //单例模式 Console.WriteLine("---------Singleton----------"); var s1 = Singleton.GetSingleton(); var s2 = Singleton.GetSingleton(); Console.WriteLine(s1.GetHashCode()); Console.WriteLine(s2.GetHashCode()); //简单工厂模式 Console.WriteLine("---------SimpleFactory----------"); var f1 = SimpleFoodFactory.CreateFood("TomaoScrambledEggs"); f1.Print(); var f2 = SimpleFoodFactory.CreateFood("ShreddedPorkWithPotatoes"); f2.Print(); //工厂模式 Console.WriteLine("---------Factory----------"); Creator shreddedPorkWithPotatoesFactory = new ShreddedPorkWithPotatoesFactory(); Creator tomatoScrambledEggsFactory = new TomatoScrambledEggsFactory(); Creator minceMeatEggplantFactor = new MincedMeatEggplantFactory(); var tomatoScrambleEggs = tomatoScrambledEggsFactory.CreateFoodFactory(); tomatoScrambleEggs.Print(); var shreddedPorkWithPotatoes = shreddedPorkWithPotatoesFactory.CreateFoodFactory(); shreddedPorkWithPotatoes.Print(); var minceMeatEggplant = minceMeatEggplantFactor.CreateFoodFactory(); minceMeatEggplant.Print(); //抽象工厂模式 Console.WriteLine("---------AbstractFactory----------"); AbstractFactory nanChangFactory = new NanChangFactory(); nanChangFactory.CreateYaBo().Print(); nanChangFactory.CreateYaJia().Print(); AbstractFactory shangHaiFactory = new ShangHaiFactory(); shangHaiFactory.CreateYaBo().Print(); shangHaiFactory.CreateYaJia().Print(); AbstractFactory huNanFactory = new HuNanFactory(); huNanFactory.CreateYaBo().Print(); huNanFactory.CreateYaJia().Print(); //建造者模式 Console.WriteLine("---------Builder_Patterns----------"); var director = new Director(); Builder b1 = new BuildFirst(); Builder b2 = new BuildSecond(); director.Construct(b1); var c1 = b1.GetComputer(); c1.Show(); director.Construct(b2); var c2 = b2.GetComputer(); c2.Show(); //原型模式 Console.WriteLine("---------Prototype_Patterns----------"); MonkeyKingPrototype prototype = new ConcretePrototype("pipixiong"); MonkeyKingPrototype cloneMonkeyKingPrototype = prototype.Clone() as ConcretePrototype; Console.WriteLine("1:" + cloneMonkeyKingPrototype?.Id); MonkeyKingPrototype clonePrototype = prototype.Clone() as ConcretePrototype; Console.WriteLine("2:" + cloneMonkeyKingPrototype?.Id); //适配器模式 Console.WriteLine("---------Adapter_Patterns----------"); ThreeHole threeHole = new PowerAdapter(); threeHole.Request(); //桥接模式 Console.WriteLine("---------Bridge_Patterns----------"); RemoteControl remoteControl = new ConcreteRemote(); remoteControl.Implementor = new XiaoMi(); remoteControl.On(); remoteControl.Off(); remoteControl.SetChannel(); remoteControl.Implementor = new Samsung(); remoteControl.On(); remoteControl.Off(); remoteControl.SetChannel(); //装饰者模式 Console.WriteLine("---------Decorator_Patterns----------"); Phone phone = new ApplePhone(); Decorator stickerDecorator = new Sticker(phone); stickerDecorator.Print(); Console.WriteLine("---------"); Decorator accessoriesDecorator = new Accessories(phone); accessoriesDecorator.Print(); Console.WriteLine("---------"); var sticker = new Sticker(phone); var accessories = new Accessories(sticker); accessories.Print(); //组合模式 Console.WriteLine("---------Composite_Patterns----------"); var complexGraphics = new ComplexGraphics("一个复杂图形和两条线段组成的复杂图形"); complexGraphics.Add(new Line("线A")); var complexGraphicsCG = new ComplexGraphics("一个圆和一条线组成的复杂图形"); complexGraphicsCG.Add(new Circle("圆")); complexGraphicsCG.Add(new Line("线B")); complexGraphics.Add(complexGraphicsCG); var line = new Line("线C"); complexGraphics.Add(line); Console.WriteLine("复杂图形的绘制如下:"); Console.WriteLine("---------------------"); complexGraphics.Draw(); Console.WriteLine("复杂图形绘制完成"); Console.WriteLine("---------------------"); complexGraphics.Remove(line); Console.WriteLine("移除线段C后,复杂图形的绘制如下:"); Console.WriteLine("---------------------"); complexGraphics.Draw(); Console.WriteLine("复杂图形绘制完成"); Console.WriteLine("---------------------"); //外观模式 Console.WriteLine("---------Facade_Patterns----------"); var facade = new RegistrationFacade(); if (facade.RegisterCourse("设计模式", "pomelo")) { Console.WriteLine("选课成功"); } else { Console.WriteLine("选课失败"); } //享元模式 Console.WriteLine("---------Flyweight_Patterns----------"); var externalstate = 10; var factory = new FlyweightFactory(); var flyweightA = factory.GetfFlyweight("A"); flyweightA?.Operation(externalstate); var flyweightB = factory.GetfFlyweight("B"); flyweightB?.Operation(externalstate); var flyweightC = factory.GetfFlyweight("C"); flyweightC?.Operation(externalstate); var flyweightD = factory.GetfFlyweight("D"); if (flyweightD != null) { flyweightD.Operation(externalstate); } else { Console.WriteLine("驻留池中不存在字符串D"); // 这时候就需要创建一个对象并放入驻留池中 var d = new ConcreteFlyweight("D"); factory.Flyweights.Add("D", d); } //代理模式 Console.WriteLine("---------Proxy_Patterns----------"); Person proxy = new Friend(); proxy.BuyProduct(); //模板方法 Console.WriteLine("---------Template_Patterns----------"); var spinach = new Spinach(); spinach.cookVegetable(); //命令模式 Console.WriteLine("---------Command_Patterns----------"); var receiver = new Receiver(); Command command = new ConcreteCommand(receiver); var invoke = new Invoke(command); invoke.ExecuteCommand(); //迭代器模式 Console.WriteLine("---------Iterator_Patterns----------"); IListCollection list = new ConcreteList(); var terator = list.GetITerator(); while (terator.MoveNext()) { var i = (int)terator.GetCurrent(); Console.WriteLine(i.ToString()); terator.Next(); } //观察者模式 Console.WriteLine("---------Observer_Patterns----------"); TenXun tenXun = new TenXunGame("LOL", "游戏需要更新"); tenXun.AddObserver(new Subscriber("pomelo")); tenXun.AddObserver(new Subscriber("yuuko")); tenXun.Update(); //中介者模式 Console.WriteLine("---------Mediator_Patterns----------"); AbstractCardPartner a = new ParterA(); AbstractCardPartner b = new ParterB(); a.MoneyCount = 20; b.MoneyCount = 20; AbstractMediator mediator = new MediatorPater(a, b); a.ChangCount(5, mediator); Console.WriteLine("A现在的钱是:{0}", a.MoneyCount); Console.WriteLine("B现在的钱是:{0}", b.MoneyCount); b.ChangCount(10, mediator); Console.WriteLine("A现在的钱是:{0}", a.MoneyCount); Console.WriteLine("B现在的钱是:{0}", b.MoneyCount); //状态者模式 Console.WriteLine("---------state_Patterns----------"); var account = new Account("pomelo"); account.Deposit(1000); account.Deposit(200); account.Deposit(600); account.PayInterest(); account.Withdraw(2000); account.Withdraw(500); //策略者模式 Console.WriteLine("---------stragety_Patterns----------"); var operation = new InterestOperation(new PersonalTaxStrategy()); Console.WriteLine("个人支付的税为:{0}", operation.GetTax(5000.00)); operation = new InterestOperation(new EnterpriseTaxStrategy()); Console.WriteLine("企业支付的税为:{0}", operation.GetTax(50000.00)); //责任链模式 Console.WriteLine("---------Responsibility_Patterns----------"); var purchaseRequest = new PurchaseRequest(4000, "phone"); var softPurchaseRequest = new PurchaseRequest(10000, "vs"); var computeRequest = new PurchaseRequest(40000, "computer"); Approver manager = new Manager("pomelo"); Approver vp = new VicePresident("yuuko"); Approver pre = new President("jesse"); manager.NextApprover = vp; vp.NextApprover = pre; manager.ProcessRequest(purchaseRequest); manager.ProcessRequest(softPurchaseRequest); manager.ProcessRequest(computeRequest); //访问者模式 Console.WriteLine("---------Vistor_Patterns----------"); var objectStructure = new ObjectStructure(); foreach (Element e in objectStructure.Elements) { e.Accept(new ConcreteVistor()); } //备忘录模式 Console.WriteLine("---------Memento_Patterns----------"); var persons = new List <ContactPerson> { new ContactPerson { Name = "Pomelo", MobileNum = "123445" }, new ContactPerson { Name = "Yuuko", MobileNum = "234565" }, new ContactPerson { Name = "Jeese ", MobileNum = "231455" } }; var mobileOwner = new MobileOwner(persons); mobileOwner.Show(); var caretaker = new Caretaker(); caretaker.ContactMementoDic.Add(DateTime.Now.ToString(CultureInfo.InvariantCulture), mobileOwner.CreateContactMemento()); Console.WriteLine("----移除最后一个联系人--------"); mobileOwner.ContactPersons.RemoveAt(2); mobileOwner.Show(); Thread.Sleep(1000); caretaker.ContactMementoDic.Add(DateTime.Now.ToString(CultureInfo.InvariantCulture), mobileOwner.CreateContactMemento()); Console.WriteLine("-------恢复联系人列表,请从以下列表选择恢复的日期------"); var keyCollection = caretaker.ContactMementoDic.Keys; foreach (var k in keyCollection) { Console.WriteLine("Key = {0}", k); } while (true) { Console.Write("请输入数字,按窗口的关闭键退出:"); var index = -1; try { index = int.Parse(Console.ReadLine()); } catch { Console.WriteLine("输入的格式错误"); continue; } if (index < keyCollection.Count && caretaker.ContactMementoDic.TryGetValue(keyCollection.ElementAt(index), out var contactMentor)) { mobileOwner.RestoreMemento(contactMentor); mobileOwner.Show(); } else { Console.WriteLine("输入的索引大于集合长度!"); } } }