Пример #1
0
        static void Invock22()
        {
            int extrinsicstate   = 22;
            var flyweightFactory = new FlyweightFactory();

            var flyweightX = flyweightFactory.GetFlyweight("x");

            flyweightX.Operation(--extrinsicstate);
            var flyweightY = flyweightFactory.GetFlyweight("y");

            flyweightY.Operation(--extrinsicstate);
            var flyweightZ = flyweightFactory.GetFlyweight("z");

            flyweightZ.Operation(--extrinsicstate);
            var unFlyweight = new UnSharedConcreteFlyweight();

            unFlyweight.Operation(--extrinsicstate);
        }
Пример #2
0
        static void Main(string[] args)
        {
            //1.SimpleFactory
            //Animal animal = Factory.CreatAnimal("Cat");
            //animal.PrintName();

            //2.FactoryMethod
            //CatFactory cf = new CatFactory();
            //Animal animal = cf.CreatAnimal("");
            //animal.PrintName();

            //3.AbstractFactory
            //BlueCatFactory bcf = new BlueCatFactory();
            //LittleCat cat = bcf.CreatLittleCat("");
            //cat.PrintName();

            //4.SingletonPattern
            //Singleton.instance.Print();

            //5.ObserverPattern
            //ConcreteSubject subject = new ConcreteSubject();
            //ConcreteObserver observer = new ConcreteObserver(subject);
            //subject.SetData("Data is changed!");
            //observer.Destroy();

            //6.StrategyPattern
            //Addition addition = new Addition();
            ////Multiplication multiplication = new Multiplication();
            //Calculator calculator = new Calculator(addition);
            //Console.WriteLine(calculator.Compute(10, 5).ToString());

            //7.StatePattern
            //PlayerController controller = new PlayerController(7);
            //while (true)
            //{
            //    ConsoleKeyInfo input = Console.ReadKey();
            //    switch (input.KeyChar)
            //    {
            //        case 'A':
            //            controller.PressA();
            //            break;
            //        case 'B':
            //            controller.PressB();
            //            break;
            //        case 'C':
            //            controller.PressC();
            //            break;
            //        case 'Q':
            //            return;
            //    }
            //}

            //8.DecoratorPattern
            //Component blackCoffee = new BlackCoffee();
            //blackCoffee =
            //    new Sugar(                              //4.再加糖
            //        new Milk(                           //3.再加牛奶
            //            new Sugar(                      //2.加糖
            //                new Milk(blackCoffee))));   //1.加牛奶
            //blackCoffee.Print();

            //9.CommandPattern
            //RemoteController controller = new RemoteController();
            //Light light = new Light();
            //TV tv = new TV();
            //LightOnCommand lightOn = new LightOnCommand(light);
            //LightOffCommand lightOff = new LightOffCommand(light);
            //controller.SetCommand(lightOn, lightOff);
            //controller.ClickOn();
            //controller.ClickOff();
            //TVOnCommand tvOn = new TVOnCommand(tv);
            //TVOffCommand tvOff = new TVOffCommand(tv);
            //controller.SetCommand(tvOn, tvOff);
            //controller.ClickOn();
            //controller.ClickOff();

            //10.TemplateMethod
            //ConcreteMethod1 method1 = new ConcreteMethod1();
            //Console.WriteLine("Execute method1");
            //method1.Execute();
            //ConcreteMethod2 method2 = new ConcreteMethod2();
            //Console.WriteLine("\nExecute method2");
            //method2.Execute();

            //11.AdapterPattern
            //ConcreteEnumeration enumeration = new ConcreteEnumeration();
            //ConcreteIteration iteration = new ConcreteIteration();
            //Iteration adapter = new Adapter(enumeration);
            //adapter.HasNext();
            //adapter.Next();
            //adapter.Remove(null);   //此处抛出异常

            //12.FacadePattern
            //SubSystem1 sys1 = new SubSystem1();
            //SubSystem2 sys2 = new SubSystem2();
            //SubSystem3 sys3 = new SubSystem3();
            //Facade facade = new Facade(sys1, sys2, sys3);
            //facade.Execute();

            //13.IteratorPattern
            //NameData name = new NameData();
            //ColorData color = new ColorData();
            //Iterator nameIterator = name.CreateIterator();
            //while (nameIterator.HasNext())
            //    Console.WriteLine((string)nameIterator.Next());
            //Iterator colorIterator = color.CreateIterator();
            //while (colorIterator.HasNext())
            //    Console.WriteLine((string)colorIterator.Next());

            //14.CompositePattern
            //MenuComponent rootMenu = new Menu("文件");
            //MenuComponent openMenu = new Menu("打开");
            //MenuComponent projectItem = new MenuItem("项目/解决方案");
            //MenuComponent closeItem = new MenuItem("关闭");
            //MenuComponent quitItem = new MenuItem("退出");
            //rootMenu.Add(closeItem);
            //rootMenu.Add(quitItem);
            //rootMenu.Add(openMenu);
            //openMenu.Add(projectItem);
            //rootMenu.Print();

            //15.ProxyPattern
            //Proxy proxy = Proxy.RegisterProxy("http://...");
            //if(proxy != null)
            //    proxy.Request();

            //16.BridgePattern
            //CalculatorAbstraction calculator = new Calculator();
            //calculator.strategy = new Addition();
            //Console.WriteLine(calculator.Compute(10, 5).ToString());
            //calculator.strategy = new Multiplication();
            //Console.WriteLine(calculator.Compute(10, 5).ToString());

            //17.PrototypePattern
            //ConcretePrototype prototype = new ConcretePrototype();
            //ConcretePrototype deepClone = prototype.Clone(true) as ConcretePrototype;       //深克隆
            //Console.WriteLine(prototype == deepClone);
            //Console.WriteLine(prototype.member == deepClone.member);
            //ConcretePrototype shallowClone = prototype.Clone(false) as ConcretePrototype;   //浅克隆
            //Console.WriteLine(prototype == shallowClone);
            //Console.WriteLine(prototype.member == shallowClone.member);

            //18.MementoPattern
            //System.Collections.Generic.List<ContactPerson> persons = new System.Collections.Generic.List<ContactPerson>()
            //{
            //    new ContactPerson() { name=  "张三", number = "000000000"},
            //    new ContactPerson() { name = "李四", number = "111111111"},
            //    new ContactPerson() { name = "王五", number = "222222222"}
            //};
            //Originator admin = new Originator(persons);
            //admin.Print();
            //Caretaker caretaker = new Caretaker();
            //string time = DateTime.Now.Ticks.ToString();
            //caretaker.contactMementoDic.Add(time, admin.CreateMemento());   //创建还原点
            //admin.contactPersonList.RemoveAt(0);
            //admin.Print();
            //admin.RestoreMemento(caretaker.contactMementoDic[time]);        //还原到前一个联系人状态
            //admin.Print();

            //19.BuilderPattern
            //Director director = new Director();
            //Builder b1 = new ConcreteBuilder1();
            //Builder b2 = new ConcreteBuilder2();
            //director.Construct(b1);
            //Product p1 = b1.GetFinalProduct();
            //p1.Print();
            //director.Construct(b2);
            //Product p2 = b2.GetFinalProduct();
            //p2.Print();

            //20.ChainOfResponsibility
            //ConcreteHandler1 handler1 = new ConcreteHandler1();
            //ConcreteHandler2 handler2 = new ConcreteHandler2();
            //ConcreteHandler3 handler3 = new ConcreteHandler3();
            //handler1.next = handler2;
            //handler2.next = handler3;
            //string[] requests = { "Handler2", "Handler3", "Handler1", "Handler3" };
            //foreach (string request in requests)
            //{
            //    handler1.HandleRequest(request);
            //}

            //21.InterpreterPattern
            //string english = "This is an apple.";
            //string chinese = Translator.TranslateToChinese(english);
            //Console.WriteLine(chinese);

            //22.VisitorPattern
            //ElementList elementList = new ElementList();
            //foreach (Element e in elementList.elements)
            //{
            //    e.Accept(new ConcreteVistor1());
            //    e.Accept(new ConcreteVistor2());
            //}

            //23.MediatorPattern
            //PlayerA a = new PlayerA("Player A");
            //PlayerB b = new PlayerB("Player B");
            //Mediator mediator = new Mediator(a, b);
            //mediator.ATalk();
            //mediator.BTalk();

            //24.FlyweightPattern
            FlyweightFactory factory    = new FlyweightFactory();
            FlyweightTree    poplarTree = factory.GetTree("Poplar");

            Console.WriteLine(poplarTree.ToString());
            poplarTree.height      = 5.5f;
            poplarTree.orientation = 90.0f;
            Console.WriteLine(poplarTree.ToString());
            FlyweightTree willowTree = factory.GetTree("Willow");

            willowTree.height      = 4.5f;
            willowTree.orientation = 125.0f;
            Console.WriteLine(willowTree.ToString());
            willowTree.height      = 2.5f;
            willowTree.orientation = 45.0f;
            Console.WriteLine(willowTree.ToString());

            Console.Read();
        }
Пример #3
0
        static void Main(string[] args)
        {
            #region 简单工厂

            var add = Factory.GetOperat("1");
            var sub = Factory.GetOperat("2");

            #endregion

            Console.WriteLine("------------------------------");

            #region 单例模式

            Singleton.GetInstance();
            var s1 = Singleton1.Instance;
            var s2 = Singleton2.Instance;

            #endregion

            Console.WriteLine("------------------------------");

            #region 抽象工程模式

            // ef 打开和关闭
            AbstractFactory efFactory = new EfFactory();
            efFactory.CreateOpen().Print();
            efFactory.CreateClose().Print();

            // dapper 打开和关闭
            AbstractFactory dapperFactory = new DapperFactory();
            dapperFactory.CreateOpen().Print();
            dapperFactory.CreateClose().Print();

            #endregion

            Console.WriteLine("------------------------------");

            #region 建造者模式

            var director      = new Director();
            var saiyanBuilder = new SaiyanBuilder();
            var naimBuilder   = new NaimBuilder();

            director.Construct(saiyanBuilder);

            // 组装赛亚人
            var saiyanPerson = saiyanBuilder.GetPerson();
            saiyanPerson.Show();

            // 组装那美克人
            director.Construct(naimBuilder);
            var naimPerson = naimBuilder.GetPerson();
            naimPerson.Show();

            #endregion

            Console.WriteLine("------------------------------");

            #region 原型模式

            var mingren1 = new MingrenPrototype();
            var mingren2 = mingren1.Clone() as MingrenPrototype;
            //mingren1 负责攻击
            mingren1.Attack();
            //mingren2 负责保护
            mingren2?.Protect();

            #endregion

            Console.WriteLine("------------------------------");

            #region 适配器模式

            //类的适配器模式
            var baiduMap = new BaiduAdapter();
            baiduMap.Gen();

            //对象的适配器模式
            var baiduMap1 = new BaiduAdapter1();
            baiduMap1.Gen();

            #endregion

            Console.WriteLine("------------------------------");

            #region 桥接模式

            DbControlAbstract dbControlAbstract = new DbControl();
            // Sql Server
            dbControlAbstract.Db = new SqlServerDb();
            dbControlAbstract.Open();
            dbControlAbstract.Add();
            dbControlAbstract.Close();

            // MySql
            dbControlAbstract.Db = new MySqlDb();
            dbControlAbstract.Open();
            dbControlAbstract.Add();
            dbControlAbstract.Close();

            #endregion

            Console.WriteLine("------------------------------");

            #region 装饰者模式

            // SqlServerDbHelper
            DbHelper dbHelper = new SqlServerDbHelper();
            // check
            Decorator decorator = new CheckDecorator(dbHelper);
            decorator.Add();

            #endregion

            Console.WriteLine("------------------------------");

            #region 组合模式

            //透明式
            Car car = new Motorcycle();
            car.Travel();
            car.Two(new SuvCar());
            car.Ten(new SuvCar());

            car = new SuvCar();
            car.Travel();
            car.Two(new SuvCar());
            car.Ten(new SuvCar());

            //安全式
            Car1 car1 = new Motorcycle1();
            car1.Travel();

            Car1 bus = new Bus();
            bus.Travel();
            ((FourCar)bus).Two(new Bus());
            ((FourCar)bus).Ten(new Bus());

            #endregion

            Console.WriteLine("------------------------------");

            #region 外观模式

            var facade = new Facade();
            facade.Buy();

            #endregion

            Console.WriteLine("------------------------------");

            #region 享元模式

            foreach (var item in new[] { "a", "b", "c", "a", "b" })
            {
                var flyweight = FlyweightFactory.GetFlyweight(item);
                flyweight.Operation(1);
            }
            Console.WriteLine(FlyweightFactory.DicFlyweight.Count);

            #endregion

            Console.WriteLine("------------------------------");

            #region 代理模式

            var proxy = new Proxy();
            proxy.Do("上网");

            #endregion

            Console.WriteLine("------------------------------");

            #region 模板方法模式

            var chain = new ChinaBank();
            chain.Get();
            var shBank = new ShanghaiBank();
            shBank.Get();

            #endregion

            Console.WriteLine("------------------------------");

            #region 命令模式

            var r = new Receiver1();
            var c = new CommandImp(r);
            var i = new Invoke(c);
            i.ExecuteCommand();

            #endregion

            Console.WriteLine("------------------------------");

            #region 迭代器模式

            ICollection list     = new Collection();
            var         iterator = list.GetIterator();

            while (iterator.MoveNext())
            {
                var j = (int)iterator.GetCurrent();
                Console.WriteLine(j.ToString());
                iterator.Next();
            }

            #endregion

            Console.WriteLine("------------------------------");

            #region 观察者模式

            HousingDeveloper hd = new WuhanHousingDeveloper();
            hd.Add(new NoHouseObserver("A"));
            hd.Add(new NoHouseObserver("B"));
            hd.Add(new NoHouseObserver("C"));

            hd.Add(new HasHouseObserver("D"));
            hd.Add(new HasHouseObserver("E"));
            hd.Add(new HasHouseObserver("F"));

            hd.Notify();

            #endregion

            Console.WriteLine("------------------------------");

            #region 中介者模式

            var buyer    = new Buyer();
            var seller   = new Seller();
            var mediator = new MediatorImp(buyer, seller);
            buyer.MoneyChange(5, mediator);
            seller.MoneyChange(10, mediator);

            #endregion

            Console.WriteLine("------------------------------");

            #region 状态模式

            var user = new User("admin");
            for (var j = 0; j < 10; j++)
            {
                user.Recharge(20 * j);
            }

            #endregion

            Console.WriteLine("------------------------------");

            #region 策略模式

            var context = new NotifyContext(new EmailStragety());
            context.Send("新的消息");
            context.Stragety = new SmsStragety();
            context.Send("第二条消息");

            #endregion

            Console.WriteLine("------------------------------");

            #region 责任链模式

            var leaveRequest1 = new LeaveRequest("张三", 1);
            var leaveRequest2 = new LeaveRequest("李四", 4);
            var leaveRequest3 = new LeaveRequest("王五", 7);
            var leaveRequest4 = new LeaveRequest("赵六", 11);

            Approver projectManager = new ProjectManager("项目管理者");
            Approver departManager  = new DepartManager("部门管理者");
            Approver ceo            = new Ceo("CEO");

            // 设置责任链
            projectManager.NextApprover = departManager;
            departManager.NextApprover  = ceo;

            // 处理请求
            projectManager.ProcessRequest(leaveRequest1);
            projectManager.ProcessRequest(leaveRequest2);
            projectManager.ProcessRequest(leaveRequest3);
            projectManager.ProcessRequest(leaveRequest4);

            #endregion

            Console.WriteLine("------------------------------");

            #region 访问者模式

            Visitor visitor = new VisitorImp();
            var     app     = new AppStructure(visitor);

            FinancialManagement financialManagement = new Bank();
            financialManagement.SaveMoney();
            app.Process(financialManagement);


            financialManagement = new Yeb();
            financialManagement.SaveMoney();
            app.Process(financialManagement);


            financialManagement = new Jj();
            financialManagement.SaveMoney();
            app.Process(financialManagement);

            #endregion

            Console.WriteLine("------------------------------");

            #region 备忘录模式

            var persons = new List <ContactPerson>()
            {
                new ContactPerson {
                    Name = "A", MobileNumber = "13533332222"
                },
                new ContactPerson {
                    Name = "B", MobileNumber = "13966554433"
                },
                new ContactPerson {
                    Name = "C", MobileNumber = "13198765544"
                }
            };

            //手机名单发起人
            var mobileOriginator = new MobileBackOriginator(persons);
            mobileOriginator.Show();

            // 创建备忘录并保存备忘录对象
            var manager = new MementoManager {
                ContactPersonMemento = mobileOriginator.CreateMemento()
            };

            // 更改发起人联系人列表
            Console.WriteLine("----移除最后一个联系人--------");
            mobileOriginator.ContactPersonList.RemoveAt(2);
            mobileOriginator.Show();

            // 恢复到原始状态
            Console.WriteLine("-------恢复联系人列表------");
            mobileOriginator.RestoreMemento(manager.ContactPersonMemento);
            mobileOriginator.Show();

            #endregion

            #region 解释器模式

            Console.WriteLine("------------------------------");

            const string roman = "六千四百五十二";
            var          interpreterContext = new InterpreterContext(roman);
            var          tree = new ArrayList
            {
                new GeExpression(),
                new ShiExpression(),
                new BaiExpression(),
                new QianExpression()
            };
            foreach (Expression exp in tree)
            {
                exp.Interpreter(interpreterContext);
            }
            Console.Write(interpreterContext.Data);

            #endregion

            Console.ReadKey();
        }