示例#1
0
        static void Main()
        {
            try
            {
                ProspectMemory mMamnager = new ProspectMemory();
                SalesProspect  s         = new SalesProspect();

                ChangeSalesState(s, "Noel van Halen", "(412) 256-0990", 25000.0);
                mMamnager.Insert(s.SaveMemento());

                ChangeSalesState(s, "Leo Welch", "(310) 209-7111", 1000000.0);
                mMamnager.Insert(s.SaveMemento());

                ChangeSalesState(s, "Moshe Binieli", "(972) 054-2477052", 3120000.0);
                mMamnager.Insert(s.SaveMemento());

                s.RestoreMemento(mMamnager.Get());
                s.RestoreMemento(mMamnager.Get());
                s.RestoreMemento(mMamnager.Get());
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
示例#2
0
        public void SaveProspectStateTest()
        {
            SalesProspect s = new SalesProspect
            {
                Name   = "Noel van Halen",
                Phone  = "(412) 256-0990",
                Budget = 25000.0
            };

            StringAssert.AreEqualIgnoringCase(s.Name, "Noel van Halen");
            StringAssert.AreEqualIgnoringCase(s.Phone, "(412) 256-0990");
            Assert.AreEqual(s.Budget, 25000.0);

            ProspectMemory m = new ProspectMemory {
                Memento = s.SaveMemento()
            };

            s.Name   = "Leo Welch";
            s.Phone  = "(310) 209-7111";
            s.Budget = 1000000.0;
            StringAssert.AreEqualIgnoringCase(s.Name, "Leo Welch");
            StringAssert.AreEqualIgnoringCase(s.Phone, "(310) 209-7111");
            Assert.AreEqual(s.Budget, 1000000.0);

            s.RestoreMemento(m.Memento);

            StringAssert.AreEqualIgnoringCase(s.Name, "Noel van Halen");
            StringAssert.AreEqualIgnoringCase(s.Phone, "(412) 256-0990");
            Assert.AreEqual(s.Budget, 25000.0);
        }
示例#3
0
        private static void MementoTester()
        {
            #region sample 1
            Originator o = new Originator {
                State = "On"
            };
            Caretaker c = new Caretaker {
                Memento = o.CreateMemento()
            };
            o.State = "Off";
            o.SetMemento(c.Memento);
            #endregion

            #region sample 2
            SalesProspect s = new SalesProspect
            {
                Name   = "Noel van Halen",
                Phone  = "(412) 256-0990",
                Budget = 25000.0
            };
            ProspectMemory m = new ProspectMemory {
                Memento = s.SaveMemento()
            };
            s.Name   = "Leo Welch";
            s.Phone  = "(310) 209-7111";
            s.Budget = 1000000.0;
            s.RestoreMemento(m.Memento);
            #endregion
        }
示例#4
0
        static void Main(string[] args)
        {
            Collection collection = new Collection();

            for (int i = 0; i < 8; i++)
            {
            }
            if (collection.Count > 0)
            {
                List <Iterator> iteratores = collection.CreateIterator();
                foreach (var iterator in iteratores)
                {
                    ProspectMemory m = new ProspectMemory();
                    for (ChessBoard item = iterator.Current;
                         !iterator.IsDone; item = iterator.Next())
                    {
                        Console.WriteLine(string.Format("Memento  : {0} - {1} - {2}", item.Line, item.Row, item.Parent));
                    }
                }
            }



            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            FirstDemo();

            SalesProspect s = new SalesProspect();

            s.Name   = "Noel van Halen";
            s.Phone  = "(412) 256-0990";
            s.Budget = 25000.0;

            // Store internal state

            ProspectMemory m = new ProspectMemory();

            m.Memento = s.SaveMemento();

            // Continue changing originator

            s.Name   = "Leo Welch";
            s.Phone  = "(310) 209-7111";
            s.Budget = 1000000.0;

            // Restore saved state

            s.RestoreMemento(m.Memento);

            // Wait for user

            Console.ReadKey();
        }
 private Scoreboard()
 {
     this.topFiveRecords           = new List <Player>();
     this.fileManagerFacade        = new FileManagerFacade();
     this.memory                   = new ProspectMemory();
     this.memory.ScoreboardMemento = new ScoreboardMemento(this.topFiveRecords);
     this.memory.ScoreboardMemento = this.LoadRecords();
     this.RestoreTopFive(this.memory.ScoreboardMemento);
 }
 private Scoreboard()
 {
     this.topFiveRecords = new List<Player>();
     this.fileManagerFacade = new FileManagerFacade();
     this.memory = new ProspectMemory();
     this.memory.ScoreboardMemento = new ScoreboardMemento(this.topFiveRecords);
     this.memory.ScoreboardMemento = this.LoadRecords();
     this.RestoreTopFive(this.memory.ScoreboardMemento);
 }
示例#8
0
文件: Map.cs 项目: vygantas1998/snake
 public void SaveSnakesState()
 {
     SnakesSave = new List <ProspectMemory>();
     foreach (SnakeBody s in Snakes)
     {
         ProspectMemory mem = new ProspectMemory();
         mem.Memento = s.SaveMemento();
         SnakesSave.Add(mem);
     }
 }
示例#9
0
        public void SaveMementoTest()
        {
            m = new ProspectMemory
            {
                Memento = s.SaveMemento()
            };

            Assert.AreEqual(m.Memento.Name, s.Name);
            Assert.AreEqual(m.Memento.Phone, s.Phone);
            Assert.AreEqual(m.Memento.Budget, s.Budget);
        }
示例#10
0
        public void RestoreMementoTest()
        {
            var savedMemory = new ProspectMemory
            {
                Memento = new Memento("Stored Name", "(412) 123-4567", 9000.0)
            };

            s.RestoreMemento(savedMemory.Memento);

            Assert.AreEqual(s.Name, "Stored Name");
            Assert.AreEqual(s.Phone, "(412) 123-4567");
            Assert.AreEqual(s.Budget, 9000.0);
        }
示例#11
0
        internal static void Main()
        {
            var sale = new SalesProspect { Name = "Noel van Halen", Phone = "(412) 256-0990", Budget = 25000.0 };

            // Store internal state
            var memory = new ProspectMemory();
            memory.Memento = sale.SaveMemento();

            // Continue changing originator
            sale.Name = "Leo Welch";
            sale.Phone = "(310) 209-7111";
            sale.Budget = 1000000.0;

            // Restore saved state
            sale.RestoreMemento(memory.Memento);
        }
        static void Main()
        {
            //TODO 「本質がわかっていない( ゚Д゚)」
            SalesProspect s = new SalesProspect();

            s.Name   = "Noel van Halen";
            s.Phone  = "(412) 256-0990";
            s.Budget = 25000.0;
            ProspectMemory m = new ProspectMemory();

            m.Memento = s.SaveMemento();

            s.Name   = "Leo Welch";
            s.Phone  = "(310) 209-7111";
            s.Budget = 1000000.0;
            s.RestoreMemento(m.Memento);
        }
示例#13
0
        public static void Test()
        {
            SalesProspect s = new SalesProspect();

            s.Name   = "张主任";
            s.Phone  = "(020)12560990";
            s.Budget = 25000.0;
            s.Show();
            ProspectMemory m = new ProspectMemory();

            m.Memento = s.SaveMemento();
            s.Name    = "陈经理";
            s.Phone   = "(020)12097111";
            s.Budget  = 1000000.0;
            s.Show();
            s.RestoreMemento(m.Memento);
            s.Show();
        }
示例#14
0
        internal static void Main()
        {
            var sale = new SalesProspect {
                Name = "Noel van Halen", Phone = "(412) 256-0990", Budget = 25000.0
            };

            // Store internal state
            var memory = new ProspectMemory();

            memory.Memento = sale.SaveMemento();

            // Continue changing originator
            sale.Name   = "Leo Welch";
            sale.Phone  = "(310) 209-7111";
            sale.Budget = 1000000.0;

            // Restore saved state
            sale.RestoreMemento(memory.Memento);
        }
        public static void MementoRealWorld()
        {
            SalesProspect s = new SalesProspect();

            s.Name   = "Noel van Halen";
            s.Phone  = "(412) 256-0990";
            s.Budget = 25000.0;

            // Store internal state
            ProspectMemory m = new ProspectMemory();

            m.Memento = s.SaveMemento();

            // Continue changing originator
            s.Name   = "Leo Welch";
            s.Phone  = "(310) 209-7111";
            s.Budget = 1000000.0;

            // Restore saved state
            s.RestoreMemento(m.Memento);
        }
示例#16
0
        public void SaveAndRestoreMementoTest()
        {
            m = new ProspectMemory
            {
                Memento = s.SaveMemento()
            };

            s.Name   = "Leo Welch";
            s.Phone  = "(310) 209-7111";
            s.Budget = 1000000.0;

            Assert.AreNotEqual(m.Memento.Name, s.Name);
            Assert.AreNotEqual(m.Memento.Phone, s.Phone);
            Assert.AreNotEqual(m.Memento.Budget, s.Budget);

            s.RestoreMemento(m.Memento);

            Assert.AreEqual(m.Memento.Name, s.Name);
            Assert.AreEqual(m.Memento.Phone, s.Phone);
            Assert.AreEqual(m.Memento.Budget, s.Budget);
        }
示例#17
0
    // Entry point into console application.
    static void Main()
    {
        SalesProspect s = new SalesProspect();
        s.Name = "Bob Northrop";
        s.Phone = "(705) 123-4567";
        s.Budget = 17000.0;

        // Store internal state
        ProspectMemory m = new ProspectMemory();
        m.Memento = s.SaveMemento();

        // Continue changing originator
        s.Name = "Eve Ugly";
        s.Phone = "(416) 456-1239";
        s.Budget = 700000.0;

        // Restore saved state
        s.RestoreMemento(m.Memento);

        // Wait for user
        Console.ReadKey();
    }
示例#18
0
        /// <summary>
        /// Entry point into console application.
        /// </summary>
        public void Run()
        {
            var s = new SalesProspect
            {
                Name   = "Noel van Halen",
                Phone  = "(412) 256-0990",
                Budget = 25000.0
            };

            // Store internal state
            var m = new ProspectMemory
            {
                Memento = s.SaveMemento()
            };

            // Continue changing originator
            s.Name   = "Leo Welch";
            s.Phone  = "(310) 209-7111";
            s.Budget = 1000000.0;

            // Restore saved state
            s.RestoreMemento(m.Memento);
        }
示例#19
0
    // Entry point into console application.
    static void Main()
    {
        SalesProspect s = new SalesProspect();

        s.Name   = "Bob Northrop";
        s.Phone  = "(705) 123-4567";
        s.Budget = 17000.0;

        // Store internal state
        ProspectMemory m = new ProspectMemory();

        m.Memento = s.SaveMemento();

        // Continue changing originator
        s.Name   = "Eve Ugly";
        s.Phone  = "(416) 456-1239";
        s.Budget = 700000.0;

        // Restore saved state
        s.RestoreMemento(m.Memento);

        // Wait for user
        Console.ReadKey();
    }
示例#20
0
        public DesignPatternModule()
        {
            Get["/testStatePattern"] = _ =>
            {
                var traficLight = new TraficLight();
                var process     = traficLight.StartTheTraficLight();

                return(process);
            };

            Get["/testNullObjectPattern"] = _ =>
            {
                var dog           = new Dog();
                var dougSound     = "Dog Sound: " + dog.MakeSound() + ", ";
                var unknown       = Animal.Null;
                var noAnimalSound = "No Animal Sound: " + unknown.MakeSound();

                return(dougSound + noAnimalSound);
            };

            Get["/testObserverPattern"] = _ =>
            {
                var observable = new Observable();
                var observer   = new Observer();
                observable.SomethingHappened += observer.HandleEvent;

                var observerValue = observable.DoSomething();

                return(observerValue);
            };
            Get["/testBridgePattern/{currentSource}"] = _ =>
            {
                var currentSource = (string)_.currentSource;

                var myCustomTv = new MyCustomTv();
                switch (currentSource)
                {
                case "1":
                    myCustomTv.VideoSource = new LocalCableTv();
                    break;

                case "2":
                    myCustomTv.VideoSource = new CableColorTv();
                    break;

                case "3":
                    myCustomTv.VideoSource = new TigoService();
                    break;
                }

                var tvGuide   = myCustomTv.ShowTvGuide();
                var playVideo = myCustomTv.ShowTvGuide();

                return(tvGuide + " / " + playVideo);
            };
            Get["/testVisitorPattern"] = _ =>
            {
                var popRock      = new PopRockMusicVisitor();
                var musicLibrary = new MusicLibrary();
                var songs        = musicLibrary.Accept(popRock);

                return(songs);
            };

            Get["/testBuilderPattern"] = _ =>
            {
                var            shop    = new Shop();
                VehicleBuilder builder = new CarBuilder();
                shop.Construct(builder);
                var getBuilderProcess = builder.Vehicle.Show();
                return(getBuilderProcess);
            };
            Get["/testInterpreterPattern"] = _ =>
            {
                const string roman   = "MCMXXVIII";
                var          context = new Context(roman);

                var tree = new List <Expression>
                {
                    new ThousandExpression(),
                    new HundredExpression(),
                    new TenExpression(),
                    new OneExpression()
                };

                foreach (var exp in tree)
                {
                    exp.Interpret(context);
                }

                return("Interpreter Input: " + roman + ", Interpreter Output: " + context.Output);
            };

            Get["/testChainOfResponsabilityPattern"] = _ =>
            {
                var response = "";
                var pamela   = new Director();
                var byron    = new VicePresident();
                var colin    = new President();

                pamela.SetSuccessor(byron);
                byron.SetSuccessor(colin);

                var p = new Purchase(2034, 350.00, "Assets");
                response = pamela.ProcessRequest(p);

                p         = new Purchase(2035, 32590.10, "Project X");
                response += " / " + pamela.ProcessRequest(p);

                p         = new Purchase(2036, 90000.00, "Project Y");
                response += " / " + pamela.ProcessRequest(p);

                p         = new Purchase(2036, 122100.00, "Project Z");
                response += " / " + pamela.ProcessRequest(p);
                return(response);
            };

            Get["/testIteratorPattern"] = _ =>
            {
                var collection = new Collection();
                collection[0] = new Item("Item 0");
                collection[1] = new Item("Item 1");
                collection[2] = new Item("Item 2");
                collection[3] = new Item("Item 3");
                collection[4] = new Item("Item 4");
                collection[5] = new Item("Item 5");
                collection[6] = new Item("Item 6");
                collection[7] = new Item("Item 7");
                collection[8] = new Item("Item 8");

                var iterator = collection.CreateIterator();

                iterator.Step = 2;

                var response = "Iterating over collection:";

                for (var item = iterator.First(); !iterator.IsDone; item = iterator.Next())
                {
                    response += item.Name + " / ";
                }
                return(response);
            };

            Get["/testAdapterPattern"] = _ =>
            {
                var response = "";
                var unknown  = new Compound("Unknown");
                response += " / " + unknown.Display();

                var water = new RichCompound("Water");
                response += " / " + water.Display();

                var benzene = new RichCompound("Benzene");
                response += " / " + benzene.Display();

                var ethanol = new RichCompound("Ethanol");
                response += " / " + ethanol.Display();

                return(response);
            };

            Get["/testCommandPattern"] = _ =>
            {
                var response = "";
                var user     = new User();

                response += user.Compute('+', 100) + " / ";
                response += user.Compute('-', 50) + " / ";
                response += user.Compute('*', 10) + " / ";
                response += user.Compute('/', 2) + " / ";

                response += user.Undo(4) + " / ";
                response += user.Redo(3);
                return(response);
            };
            Get["/testFactoryPattern"] = _ =>
            {
                var response  = "";
                var documents = new Document[2];

                documents[0] = new Resume();
                documents[1] = new Report();

                foreach (var document in documents)
                {
                    response += document.GetType().Name + "--";
                    foreach (var page in document.Pages)
                    {
                        response += " " + page.GetType().Name;
                    }
                }
                return(response);
            };
            Get["/testStrategyPattern"] = _ =>
            {
                var response       = "";
                var studentRecords = new SortedList();

                studentRecords.Add("Samual");
                studentRecords.Add("Jimmy");
                studentRecords.Add("Sandra");
                studentRecords.Add("Vivek");
                studentRecords.Add("Anna");

                studentRecords.SetSortStrategy(new QuickSort());
                response += "Quicksort: " + studentRecords.Sort() + " -- ";

                studentRecords.SetSortStrategy(new ShellSort());
                response += "ShellSort: " + studentRecords.Sort() + " -- ";

                studentRecords.SetSortStrategy(new MergeSort());
                response += "MergeSort: " + studentRecords.Sort();
                return(response);
            };
            Get["/testTemplatePattern"] = _ =>
            {
                var           response = "";
                AbstractClass aA       = new ConcreteClassA();
                response += aA.TemplateMethod();

                AbstractClass aB = new ConcreteClassB();
                response += aB.TemplateMethod();
                return(response);
            };
            Get["/testFacadePattern"] = _ =>
            {
                var response = "";
                var mortgage = new Mortgage();

                var customer = new Customer("Ann McKinsey");
                var eligible = mortgage.IsEligible(customer, 125000);

                response += customer.Name + " has been " + (eligible ? "Approved" : "Rejected");
                return(response);
            };
            Get["/mediatorPattern"] = _ =>
            {
                var response = "";
                var chatroom = new Chatroom();

                Participant paul  = new Beatle("Paul");
                Participant john  = new Beatle("John");
                Participant yoko  = new NonBeatle("Yoko");
                Participant ringo = new Beatle("Ringo");

                chatroom.Register(paul);
                chatroom.Register(john);
                chatroom.Register(yoko);
                chatroom.Register(ringo);

                response += yoko.Send("John", "Hi John!") + " ";
                response += paul.Send("Ringo", "All you need is love") + " ";
                response += paul.Send("John", "Can't buy me love") + " ";
                response += john.Send("Yoko", "My sweet love");

                return(response);
            };
            Get["/testFlyweightPattern"] = _ =>
            {
                var          response = "";
                const string document = "AAZZBBZB";
                var          chars    = document.ToCharArray();

                var factory   = new CharacterFactory();
                var pointSize = 10;

                foreach (var c in chars)
                {
                    pointSize++;
                    var character = factory.GetCharacter(c);
                    response += character.Display(pointSize) + " ";
                }
                return(response);
            };
            Get["/testMomentoPattern"] = _ =>
            {
                var response = "Save Sales, Restore Memento";
                var s        = new SalesProspect
                {
                    Name   = "Noel van Halen",
                    Phone  = "(412) 256-0990",
                    Budget = 25000.0
                };

                var m = new ProspectMemory {
                    Memento = s.SaveMemento()
                };

                s.Name   = "Leo Welch";
                s.Phone  = "(310) 209-7111";
                s.Budget = 1000000.0;

                s.RestoreMemento(m.Memento);

                return(response);
            };
            Get["/testDoubleDispatchPattern"] = _ =>
            {
                var    response = "";
                object x        = 5;
                var    dispatch = new DoubleDispatch();

                response += dispatch.Foo <int>(x);
                response += dispatch.Foo <string>(x.ToString());
                return(response);
            };
            Get["/testTransactionScriptPattern"] = _ =>
            {
                var response = "";
                response += "Booked Holiday: " + HolidayService.BookHolidayFor(1, new DateTime(2016, 12, 31), new DateTime(2017, 1, 5)) + " - ";
                response += "Employes Leaving in Holiday: " + string.Join(", ", HolidayService.GetAllEmployeesOnLeaveBetween(new DateTime(2016, 12, 31),
                                                                                                                             new DateTime(2017, 1, 5)).Select(x => x.Name)) + " - ";
                response += "Employes without Holiday: " + string.Join(", ", HolidayService.GetAllEmployeesWithHolidayRemaining().Select(x => x.Name));
                return(response);
            };
        }
        static void Main(string[] args)
        {
            #region Person

            var person = new Person
            {
                Address   = "Under the Bridge 171",
                CellPhone = "122011233185",
                FirstName = "John",
                LastName  = "Doe"
            };

            var caretaker = new PersonCaretaker();
            caretaker.Add(person.CreateUnDo());

            person.ShowInfo();
            Console.WriteLine();

            person.Address = "Under the Tree 119";
            caretaker.Add(person.CreateUnDo());

            person.ShowInfo();
            Console.WriteLine();

            person.CellPhone = "987654321";
            person.ShowInfo();
            Console.WriteLine();

            person.UnDo(caretaker.GetMemento());
            person.ShowInfo();
            Console.WriteLine();

            person.UnDo(caretaker.GetMemento());
            person.ShowInfo();
            Console.WriteLine();

            #endregion

            #region Sales Prospect

            SalesProspectOriginator s = new SalesProspectOriginator
            {
                Name   = "Noel van Halen",
                Phone  = "(412) 256-0990",
                Budget = 25000.0
            };

            // Store internal state
            ProspectMemory m = new ProspectMemory
            {
                Memento = s.SaveMemento()
            };

            // Continue changing originator
            s.Name   = "Leo Welch";
            s.Phone  = "(310) 209-7111";
            s.Budget = 1000000.0;

            // Restore saved state

            s.RestoreMemento(m.Memento);

            // Wait for user

            Console.ReadKey();

            #endregion
        }
示例#22
0
  public static void Main( string[] args )
  {
    SalesProspect s = new SalesProspect();
    s.Name = "Noel van Halen";
    s.Phone = "(412) 256-0990";
    s.Budget = 25000.0;
    s.Show();

    // Store internal state
    ProspectMemory m = new ProspectMemory();
    m.Memento = s.SaveMemento();

    // Continue changing originator
    s.Name = "Leo Welch";
    s.Phone = "(310) 209-7111";
    s.Budget = 1000000.0;
    s.Show();

    // Restore saved state
    s.RestoreMemento( m.Memento );
    s.Show();

  }
示例#23
0
        static void Main(string[] args)
        {
            string srcImagePath = @"http://dev.mygemplace.com/Content/_Traders/2/jwProducts/8_Ring2_1qK1b.jpg";
            string photoName    = Path.GetFileNameWithoutExtension(srcImagePath);

            MemoryStream   memory    = new MemoryStream();
            HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create(srcImagePath);

            using (HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse())
            {
                using (BinaryReader reader = new BinaryReader(lxResponse.GetResponseStream()))
                {
                    reader.BaseStream.CopyTo(memory);
                    //Byte[] lnByte = reader.ReadBytes(1 * 1024 * 1024 * 10);
                    //using (FileStream lxFS = new FileStream("34891.jpg", FileMode.Create))
                    //{
                    //    lxFS.Write(lnByte, 0, lnByte.Length);
                    //}
                }
            }

            Bitmap photo;

            try
            {
                photo = new Bitmap(memory);
            }
            catch (ArgumentException e)
            {
                throw new FileNotFoundException(string.Format(" GDIThumbnail generator file[{0}] not found.", srcImagePath), e);
            }

            // Factory Method
            Console.WriteLine();
            Console.WriteLine("[Abstract Factory] Pattern");
            IWidgetFactory abstractFactory = new PMWidgetFactory();
            IWidgetButton  abstractButton  = abstractFactory.CreateWidgetButton();
            IWidgetDialog  abstractDialog  = abstractFactory.CreateWidgetDialog();

            abstractButton.DrawButton();
            abstractDialog.DrawWidget();

            abstractButton.SetLocation();
            abstractDialog.SetTopMost();
            //-------------------

            // FactoryMethod/Virtual Constructor
            Console.WriteLine();
            Console.WriteLine("[FactoryMethod/Virtual Constructor] Pattern");
            Creator          creator    = new ConcreteCreator();
            IAMethodDocument amDocument = creator.CreateDocument();

            amDocument.Open();
            //----------------------------------

            // Builder
            Console.WriteLine("[Builder] Pattern");
            Console.WriteLine();
            Shop            shop    = new Shop();
            IVehicleBuilder builder = new CarBuilder();

            shop.Construct(builder);
            shop.ShowVehicle();
            builder = new VeloByke();
            shop.Construct(builder);
            shop.ShowVehicle();
            //----------------------

            // Facade
            // Provides more simple unified interface instead of few interfaces some subsystem.
            // Subsystem interfaces don't keep references to facade interface.
            Console.WriteLine();
            Console.WriteLine("[Facade] Pattern");
            Facade facade = new Facade();

            facade.MethodA();
            facade.MethodB();
            //-------

            // Flyweight
            // Build a document with text
            Console.WriteLine();
            Console.WriteLine("[Flyweight] Pattern");
            string document = "AAZZBBZB";

            char[]           chars   = document.ToCharArray();
            CharacterFactory factory = new CharacterFactory();

            // extrinsic state
            int pointSize = 10;

            //For each character use a flyweight object
            foreach (char c in chars)
            {
                pointSize++;
                Character character = factory.GetCharacter(c);
                character.Display(pointSize);
            }
            //-----------

            // Proxy
            Console.WriteLine();
            Console.WriteLine("[Proxy] pattern");
            IImage proxy = new ProxyImage();

            proxy.GetSize();
            proxy.Draw();
            //--------


            //Chain Responsibilities
            Console.WriteLine();
            Console.WriteLine("[Chain of Responsibilities] pattern");
            DialogChain dc1          = new DialogChain(null);
            ButtonChain bc1          = new ButtonChain(dc1);
            DialogChain dc2          = new DialogChain(bc1);
            ButtonChain buttonChain2 = new ButtonChain(dc2);
            IRequest    request1     = new Request1();

            ((Request1)request1).Value = "QWE_RTYU";
            buttonChain2.HandleRequest(request1);

            Request2 rq2 = new Request2();

            rq2.Value = "123456";
            buttonChain2.HandleRequest(rq2);

            //----------------------

            // Command
            Console.WriteLine();
            Console.WriteLine("[Command] Pattern");
            List <SourceCommand> srcCmd = new List <SourceCommand>();

            SourceCommand scr1 = new SourceCommand();

            scr1.Command = new OpenCommand(new Receiver1("Star1"));

            SourceCommand scr2 = new SourceCommand();

            scr2.Command = new PasteCommand(new Receiver2("Paste Star 2"));

            srcCmd.Add(scr1);
            srcCmd.Add(scr2);

            TemplatedCommand <string>       templatedCommand = new TemplatedCommand <string>(delegate(string s) { Console.WriteLine("---Delegate command is executed @@@@ {0}", s); });
            TemplatedSourceCommand <string> scr3             = new TemplatedSourceCommand <string>(templatedCommand);

            scr3.ActionInvoke("1111");

            foreach (var sourceCommand in srcCmd)
            {
                sourceCommand.InvokeCommand();
            }
            //---------

            // Interpreter
            string  roman   = "MCMXXVIII";
            Context context = new Context(roman);

            // Build the 'parse tree'
            List <Expression> tree = new List <Expression>();

            tree.Add(new ThousandExpression());
            tree.Add(new HundredExpression());
            tree.Add(new TenExpression());
            tree.Add(new OneExpression());

            // Interpret
            foreach (Expression exp in tree)
            {
                exp.Interpret(context);
            }

            Console.WriteLine("{0} = {1}", roman, context.Output);

            // define booleand expression
            // (true and x) or (y and x)
            Console.WriteLine("----------------------------");
            BooleanExp     expressing;
            BooleanContext boolContext = new BooleanContext();

            expressing = new OrExp(new AndExp(new BooleanConstant("true"), new VariableExp("x")),
                                   new AndExp(new VariableExp("y"), new NotExp("x")));

            boolContext.Assign("x", false);
            boolContext.Assign("y", false);

            Console.WriteLine("Result of boolean interpreter is [{0}]", expressing.Evaluate(boolContext));
            //-------------

            // Iterator
            Console.WriteLine();
            Console.WriteLine("Pattern Iterator");
            ConcreteAggregate aggregate = new ConcreteAggregate();

            aggregate[0] = "Object 1";
            aggregate[1] = "Object 2";
            aggregate[2] = "Object 3";
            aggregate[3] = "Object 4";
            Iterator iter = aggregate.CreateIterator();

            for (object i = iter.First(); !iter.IsDone(); i = iter.Next())
            {
                Console.WriteLine("Current object [{0}]", i);
            }

            //--------------

            // Mediator
            Console.WriteLine();
            Console.WriteLine("Pattern Mediator");

            // parts could be informed about its mediator.
            ConcreteMediator cm = new ConcreteMediator(new Collegue1(), new Collegue2(), new Collegue3());

            cm.Process1AndInform23();
            cm.Process3AndInform1();
            //------------

            // Memento
            Console.WriteLine();
            Console.WriteLine("Pattern Memento");

            SalesProspect salesProspect = new SalesProspect();

            salesProspect.Budget = 45.56;
            salesProspect.Name   = "Super Man";
            salesProspect.Phone  = "45-78-96";

            ProspectMemory prospectMemory = new ProspectMemory();

            prospectMemory.Memento = salesProspect.SaveMemento();

            salesProspect.Budget = 11.11;
            salesProspect.Name   = "Spider Man";
            salesProspect.Phone  = "33-44-55";

            salesProspect.RestoreMemento(prospectMemory.Memento);
            //--------------

            // Observer (Dependents, Publish-Subscriber)
            Console.WriteLine();
            Console.WriteLine("Pattern Observer");

            Subject           subject           = new Subject();
            ConcreteObserver1 concreteObserver1 = new ConcreteObserver1();
            ConcreteObserver2 concreteObserver2 = new ConcreteObserver2();

            subject.Register(concreteObserver1);
            subject.Register(concreteObserver2);
            subject.Register(concreteObserver1);

            subject.NotifyObservers();

            subject.UnRegister(concreteObserver2);
            subject.UnRegister(concreteObserver2);

            subject.NotifyObservers();
            //------------------------------------------

            // State
            Console.WriteLine();
            Console.WriteLine("Pattern State");
            Account account = new Account("Jim Johnson");

            // Apply financial transactions
            account.Deposit(500.0);
            account.Deposit(300.0);
            account.Deposit(550.0);
            account.PayInterest();
            account.Withdraw(2000.00);
            account.Withdraw(1100.00);
            account.Deposit(50000);
            account.PayInterest();


            //------------------------------------------

            // Strategy
            // Client should knew all available strategies.
            Console.WriteLine();
            Console.WriteLine("Pattern Strategy");

            StrategyContext strategyContext = new StrategyContext(null);

            strategyContext.ContextOperationOne();
            strategyContext.ContextOperationTwo();

            strategyContext.Strategy = new ConcreteStrategy();
            strategyContext.ContextOperationOne();
            strategyContext.ContextOperationTwo();

            //------------------------------------------

            // Template Method
            Console.WriteLine();
            Console.WriteLine("Template Method");
            TemplateMethodClass tmc = new ConcreteTemplateMethodClass1();

            tmc.TemplateMethod();
            //------------------------------------------

            // Visitor
            Console.WriteLine();
            Console.WriteLine("Visitor");
            List <INode> elements = new List <INode>();

            elements.Add(new NodeType1()
            {
                Balance = 400, Name = "Qwerty"
            });
            elements.Add(new NodeType1()
            {
                Balance = 333, Name = "QasxzWe"
            });
            elements.Add(new NodeType2()
            {
                CarName = "Mersedes"
            });
            NodeVisitor visitor = new ConcreteNodeVisitor();

            foreach (var element in elements)
            {
                element.Accept(visitor);
            }

            //------------------------------------------

            ThreadTest threadTest = new ThreadTest();

            //threadTest.RunTask();
            threadTest.TestFactory();

            // Unit of Work patternt with Repository pattern
            Console.WriteLine();
            Console.WriteLine("UOW pattern");
            StudentController sc = new StudentController();

            sc.DoAction();

            MoneyPattern.Start();
            Console.Read();
        }
示例#24
0
        static void Main(string[] args)
        {
            //Behavioral Patterns
            Console.WriteLine("Behavioral");
            // Wait for user
            Console.ReadKey();

            //1 - Command
            Console.WriteLine("Command");
            Console.WriteLine("Enter Commands (ON/OFF) : ");
            string   cmd        = Console.ReadLine();
            Light    lamp       = new Light();
            ICommand switchUp   = new FlipUpCommand(lamp);
            ICommand switchDown = new FlipDownCommand(lamp);
            Switch   s          = new Switch();

            if (cmd == "ON")
            {
                s.StoreAndExecute(switchUp);
            }
            else if (cmd == "OFF")
            {
                s.StoreAndExecute(switchDown);
            }
            else
            {
                Console.WriteLine("Command \"ON\" or \"OFF\" is required");
            }
            // Wait for user
            Console.ReadKey();

            //2 - Chain of responsability
            Console.WriteLine("Chain of responsability");
            Approver rohit = new Clerk();
            Approver rahul = new AssistantManager();
            Approver manoj = new Manager();

            rohit.Successor = rahul;
            rahul.Successor = manoj;
            var loan = new Loan {
                Number = 2034, Amount = 24000.00, Purpose = "Laptop Loan"
            };

            rohit.ProcessRequest(loan);
            loan = new Loan {
                Number = 2035, Amount = 42000.10, Purpose = "Bike Loan"
            };
            rohit.ProcessRequest(loan);
            loan = new Loan {
                Number = 2036, Amount = 156200.00, Purpose = "House Loan"
            };
            rohit.ProcessRequest(loan);
            // Wait for user
            Console.ReadKey();

            //3 - Memento
            Console.WriteLine("Memento");
            SalesProspect sp = new SalesProspect();

            sp.Name   = "Noel van Halen";
            sp.Phone  = "(412) 256-0990";
            sp.Budget = 25000.0;
            // Store internal state
            ProspectMemory m = new ProspectMemory();

            m.Memento = sp.SaveMemento();
            // Continue changing originator
            sp.Name   = "Leo Welch";
            sp.Phone  = "(310) 209-7111";
            sp.Budget = 1000000.0;
            // Restore saved state
            sp.RestoreMemento(m.Memento);
            // Wait for user
            Console.ReadKey();


            //Creational Patterns
            Console.WriteLine("Creational");
            // Wait for user
            Console.ReadKey();

            //1-Singleton
            Console.WriteLine("Singleton");
            Singleton.Instance.Show();
            // Wait for user
            Console.ReadKey();

            //2-Prototype
            Console.WriteLine("Prototype");
            Developper dev = new Developper {
                Name = "Antoine", Role = "Team Leader", PrefferedLanguage = "C#", WordsPerMinute = 42
            };
            Typist typ = new Typist {
                Name = "Casper", Role = "Typist", WordsPerMinute = 175
            };

            Console.WriteLine(typ.GetDetails());
            Console.WriteLine(dev.GetDetails());
            // Wait for user
            Console.ReadKey();

            //3-AbstractFactory
            Console.WriteLine("Abstract Factory");
            DesignPatterns.Creational.AbstractFactory.Sample.VehiculeFactory honda = new HondaFactory();
            VehiculeClient hondaclient = new VehiculeClient(honda, "Regular");

            Console.WriteLine("****** Honda ******");
            Console.WriteLine(hondaclient.GetBikeName());
            Console.WriteLine(hondaclient.GetScooterName());
            VehiculeClient hondaclient2 = new VehiculeClient(honda, "Sports");

            Console.WriteLine(hondaclient.GetBikeName());
            Console.WriteLine(hondaclient.GetScooterName());
            DesignPatterns.Creational.AbstractFactory.Sample.VehiculeFactory hero = new HondaFactory();
            VehiculeClient heroclient = new VehiculeClient(hero, "Regular");

            Console.WriteLine("****** Hero ******");
            Console.WriteLine(heroclient.GetBikeName());
            Console.WriteLine(heroclient.GetScooterName());
            VehiculeClient heroclient2 = new VehiculeClient(hero, "Sports");

            Console.WriteLine(heroclient.GetBikeName());
            Console.WriteLine(heroclient.GetScooterName());
            // Wait for user
            Console.ReadKey();

            //4- Factory Method
            Console.WriteLine("Factory Method");
            DesignPatterns.Creational.FactoryMethod.Sample.VehiculeFactory factory = new ConcreteVehiculeFactory();
            IFactory scooter = factory.GetVehicule("Scooter");

            scooter.Drive(10);
            IFactory bike = factory.GetVehicule("Bike");

            bike.Drive(20);
            // Wait for user
            Console.ReadKey();

            //5- Builder
            Console.WriteLine("Builder");
            var vehicleCreator = new VehicleCreator(new HeroBuilder());

            vehicleCreator.CreateVehicle();
            var vehicle = vehicleCreator.GetVehicle();

            vehicle.ShowInfo();
            Console.WriteLine("---------------------------------------------");
            vehicleCreator = new VehicleCreator(new HondaBuilder());
            vehicleCreator.CreateVehicle();
            vehicle = vehicleCreator.GetVehicle();
            vehicle.ShowInfo();
            // Wait for user
            Console.ReadKey();

            //Structural
            Console.WriteLine("Structural");
            // Wait for user
            Console.ReadKey();

            //1 - Proxy
            Console.WriteLine("Proxy");
            ProxyClient proxy = new ProxyClient();

            Console.WriteLine("Data from Proxy Client = {0}", proxy.GetData());
            // Wait for user
            Console.ReadKey();

            //2 - Flyweight
            Console.WriteLine("Flyweight");
            ShapeObjectFactory sof   = new ShapeObjectFactory();
            IShape             shape = sof.GetShape("Rectangle");

            shape.Print();
            shape = sof.GetShape("Rectangle");
            shape.Print();
            shape = sof.GetShape("Rectangle");
            shape.Print();
            shape = sof.GetShape("Circle");
            shape.Print();
            shape = sof.GetShape("Circle");
            shape.Print();
            shape = sof.GetShape("Circle");
            shape.Print();
            int NumObjs = sof.TotalObjectsCreated;

            Console.WriteLine("\nTotal No of Objects created = {0}", NumObjs);
            // Wait for user
            Console.ReadKey();

            //3 - Facade
            Console.WriteLine("Facade");
            CarFacade facade = new CarFacade();

            facade.CreateCompleteCar();
            // Wait for user
            Console.ReadKey();

            //4 - Bridge
            Console.WriteLine("Bridge");
            IMessageSender email   = new EmailSender();
            IMessageSender queue   = new MSMQSender();
            IMessageSender web     = new WebServiceSender();
            Message        message = new SystemMessage();

            message.Subject       = "Test Message";
            message.Body          = "Hi, This is a Test Message";
            message.MessageSender = email;
            message.Send();
            message.MessageSender = queue;
            message.Send();
            message.MessageSender = web;
            message.Send();
            UserMessage usermsg = new UserMessage();

            usermsg.Subject       = "Test Message";
            usermsg.Body          = "Hi, This is a Test Message";
            usermsg.UserComments  = "I hope you are well";
            usermsg.MessageSender = email;
            usermsg.Send();
            // Wait for user
            Console.ReadKey();

            //5 - Adapter
            Console.WriteLine("Adapter");
            ITarget Itarget = new EmployeeAdapter();
            ThirdPartyBillingSystem client = new ThirdPartyBillingSystem(Itarget);

            client.ShowEmployeeList();
            // Wait for user
            Console.ReadKey();

            //6 - Decorator
            Console.WriteLine("Decorator");
            HondaCity car = new HondaCity();

            Console.WriteLine("Honda City base price are : {0}", car.Price);
            SpecialOffer offer = new SpecialOffer(car);

            offer.DiscountPercentage = 25;
            offer.Offer = "25 % discount";
            Console.WriteLine("{1} @ Diwali Special Offer and price are : {0} ", offer.Price, offer.Offer);
            // Wait for user
            Console.ReadKey();
        }