// void UnitTest2 () { Originator theOriginator = new Originator(); Caretaker theCaretaker = new Caretaker(); // 設定資訊 theOriginator.SetInfo( "Version1" ); theOriginator.ShowInfo(); // 保存 theCaretaker.AddMemento("1",theOriginator.CreateMemento()); // 設定資訊 theOriginator.SetInfo( "Version2" ); theOriginator.ShowInfo(); // 保存 theCaretaker.AddMemento("2",theOriginator.CreateMemento()); // 設定資訊 theOriginator.SetInfo( "Version3" ); theOriginator.ShowInfo(); // 保存 theCaretaker.AddMemento("3",theOriginator.CreateMemento()); // 退回到第2版, theOriginator.SetMemento( theCaretaker.GetMemento("2")); theOriginator.ShowInfo(); // 退回到第1版, theOriginator.SetMemento( theCaretaker.GetMemento("1")); theOriginator.ShowInfo(); }
// Entry point into console application. static void Main() { Originator o = new Originator("On"); // o.State = "On"; // Store Originator's internal state within Memento inside Caretaker Caretaker c = new Caretaker(o.CreateMemento()); // c.Memento = o.CreateMemento(); // Change Originator's state o.State = "Off"; // Restore Originator's previously saved state o.SetMemento(c.Memento); // Change Originator's state again o.State = "Off"; // Store Originator's internal state within Memento inside Caretaker c = new Caretaker(o.CreateMemento()); // Change Originator's state o.State = "On"; // Restore Originator's previously saved state o.SetMemento(c.Memento); // Wait for user Console.ReadKey(); }
static void Main() { Originator originator = new Originator(); originator.State = "On"; // Store internal state Caretaker c = new Caretaker(); c.Memento = originator.CreateMemento(); // Continue changing originator originator.State = "Off"; // Restore saved state originator.SetMemento(c.Memento); }
public static void Main( string[] args ) { Originator o = new Originator(); o.State = "On"; // Store internal state Caretaker c = new Caretaker(); c.Memento = o.CreateMemento(); // Continue changing originator o.State = "Off"; // Restore saved state o.SetMemento( c.Memento ); Console.Read(); }
/// <summary> /// Entry point into console application. /// </summary> static void Demo() { Originator o = new Originator(); o.State = "On"; // Store internal state Caretaker c = new Caretaker(); c.Memento = o.CreateMemento(); // Continue changing originator o.State = "Off"; // Restore saved state o.SetMemento(c.Memento); // Wait for user Console.ReadKey(); }
// The 'Originator' class public void TestMementoPattern() { var o = new Originator(); o.State = "On"; // Store internal state var c = new Caretaker(); c.Memento = o.CreateMemento(); // Continue changing originator o.State = "Off"; // Restore saved state o.SetMemento(c.Memento); // Wait for user Console.ReadKey(); }
// void UnitTest () { Originator theOriginator = new Originator(); // 設定資訊 theOriginator.SetInfo( "Step1" ); theOriginator.ShowInfo(); // 儲存狀態 Memento theMemnto = theOriginator.CreateMemento(); // 設定新的資訊 theOriginator.SetInfo( "Step2" ); theOriginator.ShowInfo(); // 復原 theOriginator.SetMemento( theMemnto ); theOriginator.ShowInfo(); }
static void Main(string[] args) { Originator originator = new Originator(); originator.State = "On"; Console.WriteLine(originator.State); Caretaker caretaker = new Caretaker(); caretaker.Memento = originator.CreateMemento(); originator.State = "Off"; Console.WriteLine(originator.State); originator.SetMemento(caretaker.Memento); Console.WriteLine(originator.State); Console.Read(); }
//Зберігач - Token, Memento public Run Memento() { Console.WriteLine("\nMemento:"); Originator o = new Originator(); o.State = "On"; // Store internal state Caretaker c = new Caretaker(); c.Memento = o.CreateMemento(); // Continue changing originator o.State = "Off"; // Restore saved state o.SetMemento(c.Memento); return(this); }
public void Start() { Originator o = new Originator(); o.State = "Open"; // Store internal state Caretaker c = new Caretaker(); c.Memento = o.CreateMemento(); // Continue changing originator o.State = "Closed"; o.State = "Sealed"; // Restore saved state o.SetMemento(c.Memento); }
public static void Main() { var originator1 = new Originator("Originator"); originator1.Append("List of Programming Languages\n"); originator1.Append("C++"); originator1.Append("Java"); originator1.Append("C#"); originator1.Append("Python"); originator1.Append("Groovy"); originator1.Append("Ruby"); var memento = originator1.CreateMemento(); var originator2 = new Originator(); originator2.SetMemento(memento); originator2.Print(); Console.ReadKey(); }
private static void Test() { // 实例化发起人类 Originator o = new Originator(); // 发起人状态为开启 o.State = "On"; o.Show(); // 实例化管理者类 Caretaker c = new Caretaker(); // 管理者开始管理备忘录 (内部关联备忘录)备份备忘录 c.Memento = o.CreateMemento(); // 发起人状态改变 o.State = "Off"; o.Show(); // 发起人恢复备忘录 o.SetMemento(c.Memento); o.Show(); }
public void MementoTest() { { var orig = new Originator(); orig.Show(); var caretaker = new Creataker { Memento = orig.CreateMemento() }; orig.SetState("2"); orig.Show(); orig.RestoreMemento(caretaker.Memento); orig.Show(); } { var mobileOwner = new MobileOwner(); mobileOwner.Show(); var caretaker = new Caretaker { ContactM = mobileOwner.CreateMemento() }; mobileOwner.ContactPersons.RemoveAt(1); mobileOwner.Show(); mobileOwner.ContactPersons.Clear(); mobileOwner.Show(); mobileOwner.RestoreMemento(caretaker.ContactM); mobileOwner.Show(); } }
static void Main(string[] args) { #region Strategy //First Step Console.WriteLine("Initialize Strategy"); long[] inputArray = new long[20]; Random radom = new Random(); for (int strategy = 0; strategy < inputArray.Length; strategy++) { inputArray[strategy] = radom.Next(100); } foreach (long number in inputArray) { Console.WriteLine(number); } Console.ReadKey(); //Second Step //Strategy 1 var alg = new BubbleSort(); alg.Sort(inputArray); Console.WriteLine("sort numbers"); foreach (long number in inputArray) { Console.WriteLine(number); } Console.ReadKey(); //Strategy 2 var alg2 = new SelectionSort(); alg2.Sort(inputArray); Console.WriteLine("sort numbers"); foreach (long number in inputArray) { Console.WriteLine(number); } Console.ReadKey(); //Apply Strategy Patterns Strategy.Context ctx = new Strategy.Context(new SelectionSort()); ctx.ContextInterface(inputArray); Console.WriteLine("sort numbers"); foreach (long number in inputArray) { Console.WriteLine(number); } Console.ReadKey(); Console.WriteLine("Finalize Strategy" + Environment.NewLine); #endregion #region ChainOfResponsability Console.WriteLine("ChainOfResponsability Initialize"); // First Step Validate validate = new Validate(); Console.WriteLine(validate.ValidateUser("Test", "Test").ToString()); ///Apply ChainOfResponsability pattern ChainOfResponsability.Form valform = new ChainOfResponsability.Form(); ChainOfResponsability.Server valserver = new ChainOfResponsability.Server(); BD valBD = new BD(); valform.setSucessor(valserver); valserver.setSucessor(valBD); Console.WriteLine(valform.ValidateUser("Teste", "Teste").ToString()); Console.WriteLine("ChainOfResponsability Finalize" + Environment.NewLine); #endregion #region Command Console.WriteLine("Command Initialize"); //Configure Receiver Command.Server server = new Command.Server(); //Create command and configure receiver. CommandAbstract cmd = new ServerCommand(server); //Configure invoker Command.Formulario form = new Command.Formulario(); form.SetCommand(cmd); form.ClickValidate(); Console.WriteLine("Command Finalize" + Environment.NewLine); Console.ReadLine(); #endregion #region Iterator Console.WriteLine("Iterator Initialize"); //Create concrete aggregate Team team = new Team(); team[0] = "Luiz"; team[0] = "Alex"; team[0] = "Rodrigo"; team[0] = "Renan"; ConcreteIterator i = new ConcreteIterator(team); Console.WriteLine("Show team's members"); Object item = i.First(); while (item != null) { Console.WriteLine(item); item = i.Next(); } Console.WriteLine("Iterator Finalize" + Environment.NewLine); Console.ReadLine(); #endregion #region Mediator Console.WriteLine("Mediator Initialize"); ConcreteMediator concreteMediator = new ConcreteMediator(); Support support = new Support(concreteMediator); User user = new User(concreteMediator); concreteMediator.Suporte = support; concreteMediator.Usuario = user; support.Send("Hello user"); user.Send("Hello support"); Console.WriteLine("Mediator Finalize" + Environment.NewLine); Console.ReadLine(); #endregion #region Memento Console.WriteLine("Memento Initialize"); //Create originator Originator people = new Originator(); people.State = "Bored"; //Create caretaker Caretaker caretaker = new Caretaker(); caretaker.Memento = people.CreateMemento(); people.State = "Happy"; Console.WriteLine("Actual State:" + people.State); people.setMemento(caretaker.Memento); Console.WriteLine("Restore State: " + people.State); Console.WriteLine("Memento Finalize" + Environment.NewLine); #endregion #region Observer Console.WriteLine("Observer Initialize"); Balance balanco = new Balance(); Sale venda = new Sale(balanco); balanco.Attach(venda); balanco.Iniciar(); balanco.Notify(); balanco.Finalizar(); balanco.Notify(); venda.Iniciar(); //After remove observer balanco.Detach(venda); balanco.Iniciar(); balanco.Notify(); venda.Iniciar(); Console.WriteLine("Observer Finalize" + Environment.NewLine); Console.ReadLine(); #endregion #region State Console.WriteLine("State Initialize"); Connection connection = new Connection(new ConnectionOpened()); connection.Open(); connection.Close(); Console.WriteLine("State Finalize" + Environment.NewLine); Console.ReadLine(); #endregion #region Template Method Console.WriteLine("Template Method Initialize"); Correction proofCorrecion = new ProofCorrection(); proofCorrecion.Process(); Correction writingCorrection = new WritingCorrection(); writingCorrection.Process(); Console.WriteLine("Template Method Finalize" + Environment.NewLine); Console.ReadLine(); #endregion #region Visitor Console.WriteLine("Visitor Initialize"); //Config structure ObjectStructure objectStructure = new ObjectStructure(); objectStructure.Attach(new ConcreteElementA()); objectStructure.Attach(new ConcreteElementB()); //Create Visitors ConcreteVisitor1 concreteVisitor1 = new ConcreteVisitor1(); ConcreteVisitor2 concreteVisitor2 = new ConcreteVisitor2(); objectStructure.Accept(concreteVisitor1); objectStructure.Accept(concreteVisitor2); Console.WriteLine("Visitor Finalize" + Environment.NewLine); Console.ReadLine(); #endregion #region Interpreter Console.WriteLine("Interpreter Initialize"); string roman = "MCMXXVIII"; Interpreter.Context context = new Interpreter.Context(roman); List <Expression> tree = new List <Expression>(); tree.Add(new ThousandExpression()); tree.Add(new HundredExpression()); tree.Add(new TenExpression()); tree.Add(new OneExpression()); foreach (Expression exp in tree) { exp.Interpret(context); } Console.WriteLine("{0} = {1}", roman, context.Output); Console.WriteLine("Interpreter Finalize" + Environment.NewLine); Console.ReadKey(); #endregion }
static void Main(string[] args) { #if DECORATOR Decorator.Person ms = new Decorator.Person("MarsonShine"); Console.WriteLine("\n 第一种妆扮:"); TShirts dtx = new TShirts(); BigTrouser bt = new BigTrouser(); dtx.Decorate(ms); bt.Decorate(dtx); bt.Show(); #endif #if Proxy SchoolGirl zhuqin = new SchoolGirl(); zhuqin.Name = "祝琴"; Proxy.Proxy ms = new Proxy.Proxy(zhuqin); ms.GiveChocolate(); ms.GiveDolls(); ms.GiveFlowers(); Console.ReadLine(); #endif #if ChanOfResposibility HandsetBrand hb; hb = new HandsetBrandN(); hb.SetHandsetSoft(new HandsetGame()); hb.Run(); hb.SetHandsetSoft(new HandsetAddressList()); hb.Run(); HandsetBrand hb2; hb2 = new HandsetBrandM(); hb2.SetHandsetSoft(new HandsetGame()); hb2.Run(); hb2.SetHandsetSoft(new HandsetAddressList()); hb2.Run(); #endif #if ChainOfResiposibility CommonManager jinli = new CommonManager("jinli"); Majordomo zongjian = new Majordomo("zongjian"); GeneralManager zhongjingli = new GeneralManager("zhongjinli"); jinli.SetSuperior(jinli); zongjian.SetSuperior(zhongjingli); Request request = new Request(); request.RequestType = "请假"; request.RequestContent = "我要请假"; request.Number = 1; jinli.RequestApplications(request); Request request2 = new Request(); request2.RequestType = "请假"; request2.RequestContent = "我要请假"; request.Number = 4; jinli.RequestApplications(request2); Request request3 = new Request(); request3.RequestType = "请假"; request3.RequestContent = "我还是要请假"; request.Number = 500; jinli.RequestApplications(request3); #endif ObjectStructure o = new ObjectStructure(); o.Attach(new Man()); o.Attach(new Woman()); Success v1 = new Success(); o.Display(v1); Failing v2 = new Failing(); o.Display(v2); // 根据业务需求得知文件格式 var fileType = Enum.Parse <FileType>("Word"); var wordConvertor = PdfConvertorFactory.Create(fileType); wordConvertor.Convert("example.docx"); fileType = Enum.Parse <FileType>("Wps"); var wpsConvertor = PdfConvertorFactory.Create(fileType); wpsConvertor.Convert("example.wps"); // 策略模式 var vertor = new Strategy.WordToPdfConvertor(); var strategy = new StrategyContext(vertor); strategy.DoWork("example.docx"); var excel = new Strategy.ExcelToPdfConvertor(); strategy = new StrategyContext(excel); strategy.DoWork("example.xlsx"); // 策略模式+工厂模式 封装部分相同逻辑,又有部分业务不同的逻辑变化 // 抽象工厂模式 IConvertorFactory factory = new WordToPdfConvertorFactory(); Console.WriteLine("==========抽象工厂============"); factory.Create().Convert("example.docx"); // 原型模式 Console.WriteLine("==========原型模式============"); Resume r = new Resume("marson shine"); r.SetPersonalInfo("男", "27"); r.SetWorkExperience("6", "kingdee.cpl"); r.Display(); // 如果我要复制三个 Resume,则不需要实例化三次,而是调用Clone()即可 var r2 = (Resume)r.Clone(); var r3 = (Resume)r.Clone(); r2.SetWorkExperience("5", "yhglobal.cpl"); r2.Display(); r3.SetWorkExperience("3", "che100.cpl"); r3.Display(); // 观察者模式 Console.WriteLine("==========观察者模式============"); StudentOnDuty studentOnDuty = new StudentOnDuty(); var student = new StudentObserver("marson shine", studentOnDuty); studentOnDuty.Attach(student); studentOnDuty.Attach(new StudentObserver("summer zhu", studentOnDuty)); studentOnDuty.Notify(); studentOnDuty.UpdateEvent += student.Update; Console.WriteLine("==========观察者模式============"); Console.WriteLine("==========状态模式============"); var client = new Client(new PerfectState()); client.Handle(); client.Handle(); client.Handle(); Console.WriteLine("==========状态模式============"); Console.WriteLine("==========备忘录模式============"); var originator = new Originator(); originator.State = "On"; originator.Show(); MementoManager manager = new MementoManager(); manager.Record(originator.CreateMemento()); originator.State = "Off"; originator.Show(); originator.SetMemento(manager.Memento); originator.Show(); Console.WriteLine("==========备忘录模式============"); Console.WriteLine("==========规格模式============"); // 只要华为品牌的手机 ISpecification <Mobile> huaweiExpression = new ExpressionSpecification <Mobile>(p => p.Type == "华为"); // 三星手机 ISpecification <Mobile> samsungExpression = new ExpressionSpecification <Mobile>(p => p.Type == "三星"); // 华为和三星 ISpecification <Mobile> huaweiAndsamsungExpression = huaweiExpression.And(samsungExpression); List <Mobile> mobiles = new List <Mobile> { new Mobile("华为", 4888), new Mobile("三星", 6888), new Mobile("苹果", 7888), new Mobile("小米", 3888) }; var samsungs = mobiles.FindAll(p => samsungExpression.IsSatisfiedBy(p)); var huaweis = mobiles.FindAll(p => huaweiExpression.IsSatisfiedBy(p)); var samsungAndhuaweis = mobiles.FindAll(p => huaweiAndsamsungExpression.IsSatisfiedBy(p)); Console.WriteLine("==========规格模式============"); Console.WriteLine("==========时间格式化-本地文化============"); Console.WriteLine(DateTime.Now.ToString()); Console.WriteLine("ShortDatePattern:" + CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern); Console.WriteLine("LongDatePattern:" + CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern); Console.WriteLine("LongTimePattern:" + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern); CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone(); culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd"; culture.DateTimeFormat.LongTimePattern = "h:mm:ss.fff"; CultureInfo.CurrentCulture = culture; Console.WriteLine(DateTime.Now.ToString()); Console.WriteLine("开始后台线程时间格式化"); Task.Run(() => { Console.WriteLine("后台线程:" + DateTime.Now.ToString()); }); Console.WriteLine("==========时间格式化-本地文化============"); }
public void Backup() { _mementos.Push(_originator.CreateMemento()); }
public async Task CheckWord(string word, string username) { h1.SetSuccessor(h2); h2.SetSuccessor(h3); h3.SetSuccessor(h4); double chainPoints = h1.HandleRequest(word, givenWord); if (chainPoints >= 1) { parametersGroup.Accept(new ColorVisitor()); if (parametersGroup.getParameter(0).Opacity > 0.1) { parametersGroup.Accept(new OpacityVisitor()); parametersGroup.Accept(new FontSizeVisitor()); } Console.WriteLine("params"); Console.WriteLine("Color: " + parametersGroup.getParameter(0).Color); Console.WriteLine("Opacity: " + parametersGroup.getParameter(0).Opacity); Console.WriteLine("FontSize: " + parametersGroup.getParameter(0).FontSize); await Clients.All.SendAsync( "ReceiveWordStyle", Math.Round(parametersGroup.getParameter(0).Opacity, 2), Math.Round(parametersGroup.getParameter(0).FontSize, 2), parametersGroup.getParameter(0).Color); List <Player> playerListCopy = new List <Player>(); playerList.ForEach(delegate(Player player) { playerListCopy.Add((Player)player.Clone()); }); originator.State = playerListCopy; caretaker.Memento = originator.CreateMemento(); } if (chainPoints < 1) { for (int i = 0; i < playerList.Count; i++) { if (playerList[i].username == username) { playerList[i].points = playerList[i].points + Convert.ToInt32(10 * chainPoints); } } await Clients.All.SendAsync("ReceiveAllUsernames", playerList); } else { await Clients.Caller.SendAsync("GetWinMessage", lastAbilityUser); await Clients.Others.SendAsync("GetLoseMessage"); await Clients.All.SendAsync("SeasonState", _stateContext.State.GetType().Name); _stateContext.Request(); Singleton.Instance.EndTime = DateTime.Now; await Clients.All.SendAsync("ReceiveTimer", Singleton.Instance.Difference()); for (int i = 0; i < playerList.Count; i++) { playerList[i].receivedEmoji = ""; playerList[i].receivedFrom = ""; if (playerList[i].username == username) { WinnerLoser winnerLoser = new WinnerLoser(playerList[i]); winnerLoser.SetWinner(); playerList[i].points = playerList[i].points + Convert.ToInt32(10 * chainPoints) + abilityXpRate * xpRate * playerList[i].characterKoeficient; Console.WriteLine("CheckWord abilityXPRate " + abilityXpRate); } else { WinnerLoser winnerLoser = new WinnerLoser(playerList[i]); winnerLoser.SetLoser(); } if (playerList[i].talisman != null) { Console.WriteLine("Suveike vartotojo talismanas"); int points = playerList[i].talisman.ActivateTalisman(); playerList[i].points += points; Console.WriteLine("Pridedama: " + playerList[i].username + " talismano tasku: " + points); } if (playerList[i].points >= 100) { await Clients.All.SendAsync("RedirectToLobby", playerList[i].username); endGame(); return; } } if (abilityXpRate != 1) { lastAbilityUser = ""; abilityXpRate = 1; Console.WriteLine("CheckWord abilityXPRate =1"); } if (observer.SubjectState == 4) { playerList = facade.ChangeToSecondLevel(playerList); foreach (var player in playerList) { player.permissionProxy.giveShopPermission(); } } if (observer.SubjectState == 9) { playerList = facade.ChangeToThirdLevel(playerList); } await Clients.All.SendAsync("ReceiveAllUsernames", playerList); if (usedClone) { givenWord = lastWord.word; usedClone = false; } else { iterator.Step = 1; givenWord = iterator.Next().word; } Console.WriteLine("Last word: " + lastWord.word); Console.WriteLine("Game word: " + givenWord); WordPrototype gameWord = new WordPrototype(givenWord); lastWord = (WordPrototype)gameWord.Clone(); await Clients.All.SendAsync("ReceiveCountdown", 5, givenWord); observer.SubjectState++; observer.Notify(); await Clients.All.SendAsync("GetGameRound", observer.SubjectState); } }
static void Main(string[] args) { // Abstract factory IFactory concreteFactory = new WindowsFactory(); var obj1 = concreteFactory.CreateCloneable(); var obj2 = concreteFactory.CreateComparable(); // Builder IBuilder builder = new Builder1(); var director = new Director(builder); var product = director.Construct <IProduct>(); // Factory method Application app = new DrawingApplication(); Document document = app.CreateDocument(); // Prototype Prototype prototype = new ConcretePrototype1(); Prototype newObject = prototype.Clone(); // Command Receiver receiver = new Receiver(); Command command = new ConcreteCommand(receiver); Invoker invoker = new Invoker(); invoker.SetCommand(command); invoker.ExecuteCommand(); // Interpreter var context = new Context(); AbstrcatExpression experssion1 = new NonterminalExpression(); AbstrcatExpression expression2 = new TerminalExpression(); experssion1.Interpret(context); expression2.Interpret(context); // Mediator ConcreteMediator m = new ConcreteMediator(); ConcreteColleague1 c1 = new ConcreteColleague1(m); ConcreteColleague2 c2 = new ConcreteColleague2(m); m.Colleague1 = c1; m.Colleague2 = c2; c1.Send("How are you?"); c2.Send("Fine, thanks"); // Memoto Originator o = new Originator(); o.State = "On"; // Store internal state Caretaker c = new Caretaker(); c.Memento = o.CreateMemento(); // Continue changing originator o.State = "Off"; // Restore saved state o.SetMemento(c.Memento); // Observer ConcreteSubject s = new ConcreteSubject(); s.Attach(new ConcreteObserver(s, "X")); s.Attach(new ConcreteObserver(s, "Y")); s.Attach(new ConcreteObserver(s, "Z")); // Change subject and notify observers s.SubjectState = "ABC"; s.Notify(); }
public void Backup() { Mementos.Push(Originator.CreateMemento()); }
public static void SaveState(Originator <T> orig) { mementoLst.Add(orig.CreateMemento()); }
/// <summary> /// Raises the save button clicked event. /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='e'> /// E. /// </param> protected void OnSaveButtonClicked(object sender, System.EventArgs e) { originator.state = mainTextView.Buffer.Text; careTaker.AddMemento(originator.CreateMemento()); }
public void SetPlayerState(GameObject player) { originator.PlayerState = player; this.player = player; careTaker.Memento = originator.CreateMemento(); }