Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            //定义外部状态,
            int externalstate = 10;

            //初始化享元工厂
            FlyweightFactory factory = new FlyweightFactory();

            //判断是否已经创建了字母A,如果已经创建就直接使用床架你的对象A
            Flyweight fa = factory.GetFlyweight("A");

            if (fa != null)
            {
                //把外部状态作为享元对象的方法调用参数
                fa.Operation(externalstate);
            }

            //判断是否已经创建了字母D
            Flyweight fd = factory.GetFlyweight("D");

            if (fd != null)
            {
                fd.Operation(externalstate);
            }
            else
            {
                Console.WriteLine("驻留池中不存在对象D");
                //这时候就需要创建一个对象并放入驻留池中
                ConcreteFlyweight d = new ConcreteFlyweight("D");
                factory.flyweights.Add("D", d);
            }
            Console.ReadKey();
        }
Ejemplo n.º 2
0
        public static void Run()
        {
            Console.WriteLine("This structural code demonstrates the Flyweight pattern in which a relatively small number of objects is shared many times by different clients.");

            int extrinsicstate = 22;

            FlyweightFactory factory1 = new FlyweightFactory();

            Flyweight fx = factory1.GetFlyweight("X");

            fx.Operation(--extrinsicstate);

            Flyweight fy = factory1.GetFlyweight("Y");

            fy.Operation(--extrinsicstate);

            Flyweight fz = factory1.GetFlyweight("Z");

            fz.Operation(--extrinsicstate);

            UnsharedConcreteFlyweight fu = new UnsharedConcreteFlyweight();

            fu.Operation(--extrinsicstate);

            /*
             *  ConcreteFlyweight: 21
             *  ConcreteFlyweight: 20
             *  ConcreteFlyweight: 19
             *  UnsharedConcreteFlyweight: 18
             */
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            // Arbitrary extrinsic state

            int extrinsicstate = 22;

            FlyweightFactory factory = new FlyweightFactory();

            // Work with different flyweight instances

            Flyweight fx = factory.GetFlyweight("X");

            fx.Operation(--extrinsicstate);

            Flyweight fy = factory.GetFlyweight("Y");

            fy.Operation(--extrinsicstate);

            Flyweight fz = factory.GetFlyweight("Z");

            fz.Operation(--extrinsicstate);

            UnsharedConcreteFlyweight fu = new

                                           UnsharedConcreteFlyweight();

            fu.Operation(--extrinsicstate);

            // Wait for user

            Console.ReadKey();
        }
Ejemplo n.º 4
0
        static void Main()
        {
            var factoryFlyweight = new FlyweightFactory();

            #region Static Flyweight

            Console.WriteLine("Создание разделяемых (статичных) объектов");

            var flyweightA = factoryFlyweight.GetFlyweight("a");
            flyweightA.Operation(500);

            var duplicateFlyweightA = factoryFlyweight.GetFlyweight("a");
            duplicateFlyweightA.Operation(1);

            int stateA = (flyweightA as ConcreteFlyweight).objectState;
            Console.WriteLine($"a: {stateA}");

            #endregion

            #region Dynamic Flyweight

            Console.WriteLine("Создание неразделяемых (динамических) экземпляров");

            var dynamicFlyweightB = new UnsharedConcreteFlyweight();
            dynamicFlyweightB.Operation(7);
            Console.WriteLine($"b: {dynamicFlyweightB.instanceState}");

            #endregion

            Console.ReadKey();
        }
Ejemplo n.º 5
0
        static void Main()
        {
            int
                extrinsicstate = 22;

            FlyweightFactory
                factory = new FlyweightFactory();

            Flyweight
                fx = factory.GetFlyweight("X");

            fx.Operation(--extrinsicstate);

            Flyweight
                fy = factory.GetFlyweight("Y");

            fy.Operation(--extrinsicstate);

            Flyweight
                fz = factory.GetFlyweight("Z");

            fz.Operation(--extrinsicstate);

            UnsharedConcreteFlyweight
                fu = new UnsharedConcreteFlyweight();

            fu.Operation(--extrinsicstate);
        }
        static void Main(string[] args)
        {
            try
            {
                int extrinsicstate = 22;

                FlyweightFactory factory = new FlyweightFactory();

                Flyweight fx = factory.GetFlyweight("X");
                fx.Operation(--extrinsicstate);

                Flyweight fy = factory.GetFlyweight("Y");
                fy.Operation(--extrinsicstate);

                Flyweight fz = factory.GetFlyweight("Z");
                fz.Operation(--extrinsicstate);

                UnsharedConcreteFlyweight fu = new

                                               UnsharedConcreteFlyweight();

                fu.Operation(--extrinsicstate);
            }
            finally
            {
                Console.ReadKey();
            }
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            #region 结构实现
            // Arbitrary extrinsic state
            int extrinsicstate       = 22;
            FlyweightFactory factory = new FlyweightFactory();

            // Work with different flyweight instances
            Structural.Flyweight fx = factory.GetFlyweight("X");
            fx.Operation(--extrinsicstate);

            Structural.Flyweight fy = factory.GetFlyweight("Y");
            fy.Operation(--extrinsicstate);

            Structural.Flyweight fz = factory.GetFlyweight("Z");
            fz.Operation(--extrinsicstate);

            UnsharedConcreteFlyweight fu = new UnsharedConcreteFlyweight();
            fu.Operation(--extrinsicstate);
            #endregion

            Console.WriteLine("******************************");

            #region 实践应用
            #endregion

            Console.ReadKey();
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Entry point into console application.
        /// </summary>
        static void Main()
        {
            // Arbitrary extrinsic state
            int extrinsicstate = 22;

            FlyweightFactory factory = new FlyweightFactory();

            // Work with different flyweight instances
            Flyweight fx = factory.GetFlyweight("X");
            fx.Operation(--extrinsicstate);

            Flyweight fy = factory.GetFlyweight("Y");
            fy.Operation(--extrinsicstate);

            Flyweight fz = factory.GetFlyweight("Z");
            fz.Operation(--extrinsicstate);

            UnsharedConcreteFlyweight fu = new
              UnsharedConcreteFlyweight();

            fu.Operation(--extrinsicstate);

            // Wait for user
            Console.ReadKey();
        }
Ejemplo n.º 9
0
        public static void Main(string[] args)
        {
            IFlyweightFactory factory = new FlyweightFactory();

            var a = factory.GetFlyweight('a');

            Console.WriteLine($"{a.id}");

            var b = factory.GetFlyweight('b');

            Console.WriteLine($"{b.id}");

            var c = factory.GetFlyweight('b');

            Console.WriteLine($"{c.id}");

            var d = factory.GetFlyweight('d');

            Console.WriteLine($"{d.id}");

            // OUTPUT
            // 594
            // 899
            // 899
            // 401
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            //externo
            int ext = 10;

            FlyweightFactory fabrica = new FlyweightFactory();

            Flyweight f1 = fabrica.getFlyweight("A");

            f1.Operation(ext++);

            Flyweight f2 = fabrica.getFlyweight("B");

            f2.Operation(ext++);
            Flyweight f3 = fabrica.getFlyweight("C");

            f3.Operation(ext++);
            Flyweight f4 = fabrica.getFlyweight("A");

            f4.Operation(ext++);

            Flyweight f5 = new UnsharedConcreteFlyweight();

            f5.Operation(ext++);

            Console.ReadLine();
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            string           extrinsicstate = "THIS IS A BIG EXTRINSIC STATE";
            FlyweightFactory factory        = new FlyweightFactory();

            UnsharedConcreteFlyWeight flyWeight1 = new UnsharedConcreteFlyWeight(new Flyweight[]
            {
                factory.GetFlyweight('a'),
                factory.GetFlyweight('a'),
                factory.GetFlyweight('b'),
                factory.GetFlyweight('c'),
                factory.GetFlyweight('a'),
                factory.GetFlyweight('c'),
            });

            UnsharedConcreteFlyWeight flyWeight2 = new UnsharedConcreteFlyWeight(new Flyweight[]
            {
                factory.GetFlyweight('c'),
                factory.GetFlyweight('b'),
                factory.GetFlyweight('b'),
                factory.GetFlyweight('a'),
                factory.GetFlyweight('c'),
                factory.GetFlyweight('b'),
            });

            flyWeight1.Operation(extrinsicstate);
            flyWeight2.Operation(extrinsicstate);


            Console.ReadKey();
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            FlyweightFactory flyweightFactory = new FlyweightFactory();
            ConcreteObject   concreteObject1  = new ConcreteObject(1, flyweightFactory.GetFlyweight(FlyweightType.Type1));
            ConcreteObject   concreteObject2  = new ConcreteObject(1, flyweightFactory.GetFlyweight(FlyweightType.Type1));
            ConcreteObject   concreteObject3  = new ConcreteObject(1, flyweightFactory.GetFlyweight(FlyweightType.Type1));

            // Same reference in memory
            Console.Write((concreteObject1.Shared == concreteObject2.Shared) && (concreteObject2.Shared == concreteObject3.Shared));
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            int extrinsicstate = 22;

            FlyweightFactory factory = new FlyweightFactory();

            Flyweight fx = factory.GetFlyweight("X");

            fx.Operation(--extrinsicstate);

            Flyweight fy = factory.GetFlyweight("Y");

            fy.Operation(--extrinsicstate);

            Flyweight fz = factory.GetFlyweight("Z");

            fz.Operation(--extrinsicstate);

            Flyweight uf = new UnsharedConcreteFlyweight();

            uf.Operation(--extrinsicstate);

            Console.WriteLine();

            WebSiteFactory webSiteFactory = new WebSiteFactory();

            WebSite wx = webSiteFactory.GetWebSiteCategory("產品展示");

            wx.Use(new User("小菜"));

            WebSite wy = webSiteFactory.GetWebSiteCategory("產品展示");

            wy.Use(new User("大鳥"));

            WebSite wz = webSiteFactory.GetWebSiteCategory("產品展示");

            wz.Use(new User("嬌嬌"));

            WebSite wl = webSiteFactory.GetWebSiteCategory("部落格");

            wl.Use(new User("老頭"));

            WebSite wm = webSiteFactory.GetWebSiteCategory("部落格");

            wm.Use(new User("明明"));

            WebSite wn = webSiteFactory.GetWebSiteCategory("部落格");

            wn.Use(new User("寶寶"));

            Console.WriteLine($"網站分類總數為: {webSiteFactory.GetWebStieCount()}");

            Console.ReadLine();
        }
        public static void addCarToPoliceDatabase(FlyweightFactory factory, Car car)
        {
            Console.WriteLine("\nClient: Adding a car to database.");

            var flyweight = factory.GetFlyweight(new Car
            {
                Color   = car.Color,
                Model   = car.Model,
                Company = car.Company
            });

            flyweight.Operation(car);
        }
Ejemplo n.º 15
0
        public static void addCarToPoliceDatabase(FlyweightFactory factory, Ticket ticket)
        {
            Console.WriteLine("\nClient: Adding a ticket to database.");

            var flyweight = factory.GetFlyweight(new Ticket
            {
                Train = ticket.Train,
                Price = ticket.Price,
                Route = ticket.Route
            });

            flyweight.Operation(ticket);
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            // 定义外部状态,例如字母的位置等信息
            int extrinsicstate = 10;

            // 初始化享元工厂
            FlyweightFactory factory = new FlyweightFactory();

            // 判断是否创建了字母A,如果已经创建就直接使用创建的对象A
            Flyweight fa = factory.GetFlyweight("A");

            if (fa != null)
            {
                // 把外部对象作为享元对象的方法调用参数
                fa.Operation(--extrinsicstate);
            }

            // 判断是否创建了字母B,如果已经创建就直接使用创建的对象B
            Flyweight fb = factory.GetFlyweight("B");

            if (fb != null)
            {
                fb.Operation(--extrinsicstate);
            }

            // 判断是否创建了字母C,如果已经创建就直接使用创建的对象C
            Flyweight fc = factory.GetFlyweight("C");

            if (fc != null)
            {
                fc.Operation(--extrinsicstate);
            }

            // 判断是否创建了字母D,如果已经创建就直接使用创建的对象D
            Flyweight fd = factory.GetFlyweight("D");

            if (fd != null)
            {
                fd.Operation(--extrinsicstate);
            }
            else
            {
                Console.WriteLine("驻留池中不存在字符串D");
                // 这时候需要创建一个对象并放入驻留池中
                ConcreteFlyweight d = new ConcreteFlyweight("D");
                factory.flyweights.Add("D", d);
            }

            Console.ReadLine();
        }
Ejemplo n.º 17
0
        public static void addCarToPoliceDatabase(FlyweightFactory factory, Car car)
        {
            Console.WriteLine("\nClient: Adding a car to database.");

            var flyweight = factory.GetFlyweight(new Car {
                Color   = car.Color,
                Model   = car.Model,
                Company = car.Company
            });

            // Клиентский код либо сохраняет, либо вычисляет внешнее состояние и
            // передает его методам легковеса.
            flyweight.Operation(car);
        }
Ejemplo n.º 18
0
        private static void AddCarToPoliceDatabase(FlyweightFactory factory, Car car)
        {
            Console.WriteLine("\nClient: Adding a car to database.");

            var flyweight = factory.GetFlyweight(new Car {
                Color   = car.Color,
                Model   = car.Model,
                Company = car.Company
            });

            // The client code either stores or calculates extrinsic state and
            // passes it to the flyweight's methods.
            flyweight.Operation(car);
        }
Ejemplo n.º 19
0
        private static void Main()
        {
            var extrinsicstate = 100;

            var flyweightFactory = new FlyweightFactory();

            flyweightFactory.GetFlyweight("ConcreteFlyweightA").Operation(--extrinsicstate);
            flyweightFactory.GetFlyweight("ConcreteFlyweightB").Operation(--extrinsicstate);
            flyweightFactory.GetFlyweight("ConcreteFlyweightC").Operation(--extrinsicstate);

            new UnsharedConcreteFlyweight().Operation(--extrinsicstate);

            Console.ReadKey();
        }
Ejemplo n.º 20
0
        static void Main()
        {
            int extrinsicstate = 22;

            var factory = new FlyweightFactory();
            var flyweightA = factory.GetFlyweight("A");
            flyweightA.StatefulOperation(--extrinsicstate);

            var flyweightB = factory.GetFlyweight("B");
            flyweightB.StatefulOperation(--extrinsicstate);

            var flyweightC = factory.GetFlyweight("C");
            flyweightC.StatefulOperation(--extrinsicstate);

            var unsharedFlyweight = new UnsharedFlyweight();
            unsharedFlyweight.StatefulOperation(--extrinsicstate);
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            int extrinsicState  = 22;
            FlyweightFactory ff = new FlyweightFactory();

            Flyweight fw1 = ff.getFlyweight("X");

            fw1.operation(extrinsicState--);

            Flyweight fw2 = ff.getFlyweight("Y");

            fw1.operation(extrinsicState--);

            UnsharedConcreteFlyweight ucf = new UnsharedConcreteFlyweight();

            ucf.operation(extrinsicState--);
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            List <Flyweight> flyweightList    = new List <Flyweight>();
            FlyweightFactory flyweightFactory = new FlyweightFactory();

            Console.WriteLine(GC.GetTotalMemory(true));

            //Non flyweight memory usage
            //for (int i = 0; i < 1000000; i++) fls.Add(new Flyweight(i % 10 + ""));

            //Flyweight memory usage
            for (int i = 0; i < 1000000; i++)
            {
                flyweightList.Add(flyweightFactory.GetFlyweight(i % 10 + ""));
            }

            Console.WriteLine(GC.GetTotalMemory(true));
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            // Клиентский код обычно создает кучу предварительно заполненных
            // легковесов на этапе инициализации приложения.
            var factory = new FlyweightFactory(
                new Car {
                Company = "Chevrolet", Model = "Camaro2018", Color = "pink"
            },
                new Car {
                Company = "Mercedes Benz", Model = "C300", Color = "black"
            },
                new Car {
                Company = "Mercedes Benz", Model = "C500", Color = "red"
            },
                new Car {
                Company = "BMW", Model = "M5", Color = "red"
            },
                new Car {
                Company = "BMW", Model = "X6", Color = "white"
            }
                );

            factory.listFlyweights();

            addCarToPoliceDatabase(factory, new Car
            {
                Number  = "CL234IR",
                Owner   = "James Doe",
                Company = "BMW",
                Model   = "M5",
                Color   = "red"
            });

            addCarToPoliceDatabase(factory, new Car
            {
                Number  = "CL234IR",
                Owner   = "James Doe",
                Company = "BMW",
                Model   = "X1",
                Color   = "red"
            });

            factory.listFlyweights();
        }
        static void Main(string[] args)
        {
            // The client code usually creates a bunch of pre-populated
            // flyweights in the initialization stage of the application.
            var factory = new FlyweightFactory(
                new Car {
                Company = "Chevrolet", Model = "Camaro2018", Color = "pink"
            },
                new Car {
                Company = "Mercedes Benz", Model = "C300", Color = "black"
            },
                new Car {
                Company = "Mercedes Benz", Model = "C500", Color = "red"
            },
                new Car {
                Company = "BMW", Model = "M5", Color = "red"
            },
                new Car {
                Company = "BMW", Model = "X6", Color = "white"
            }
                );

            factory.ListFlyweights();

            AddCarToPoliceDatabase(factory, new Car
            {
                Number  = "CL234IR",
                Owner   = "James Doe",
                Company = "BMW",
                Model   = "M5",
                Color   = "red"
            });

            AddCarToPoliceDatabase(factory, new Car
            {
                Number  = "CL234IR",
                Owner   = "James Doe",
                Company = "BMW",
                Model   = "X1",
                Color   = "red"
            });

            factory.ListFlyweights();
        }
Ejemplo n.º 25
0
        static void Main()
        {
            Flyweight []     flyweight = new Flyweight[100];
            FlyweightFactory factory   = new FlyweightFactory();

            for (int i = 0; i < flyweight.Length; i++)
            {
                flyweight[i] = factory.GetConcreteFlyweight("1");
                flyweight[i].Operation(ConsoleColor.Yellow);
            }

            for (int i = 0; i < flyweight.Length; i++)
            {
                flyweight[i] = factory.GetUnsharedConcreteFlyweight();
                flyweight[i].Operation(ConsoleColor.Green);
            }

            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            var factory = new FlyweightFactory(
                new Car {
                Company = "Chevrolet", Model = "Camaro2018", Color = "pingk"
            },
                new Car {
                Company = "Mercedes Benz", Model = "C300", Color = "black"
            },
                new Car {
                Company = "Mercedes Benz", Model = "C500", Color = "red"
            },
                new Car {
                Company = "BMW", Model = "M5", Color = "red"
            },
                new Car {
                Company = "BMW", Model = "X6", Color = "white"
            }
                );

            factory.listFlyweights();

            addCarToPoliceDatabase(factory, new Car
            {
                Number  = "CL234IR",
                Owner   = "James Doe",
                Company = "BMW",
                Model   = "M5",
                Color   = "red"
            });

            addCarToPoliceDatabase(factory, new Car
            {
                Number  = "CL234IR",
                Owner   = "James Doe",
                Company = "BMW",
                Model   = "X1",
                Color   = "red"
            });

            factory.listFlyweights();
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            var factory = new FlyweightFactory(
                new Ticket {
                Route = "Kyiv Lviv", Price = "2000", Train = "pink"
            },
                new Ticket {
                Route = "Che Kharkiv", Price = "300", Train = "black"
            },
                new Ticket {
                Route = "Moscow Wroclaw", Price = "500", Train = "red"
            },
                new Ticket {
                Route = "Che Khotyn", Price = "5", Train = "red"
            },
                new Ticket {
                Route = "Lviv Rivne", Price = "6", Train = "white"
            }
                );

            factory.listFlyweights();

            addCarToPoliceDatabase(factory, new Ticket
            {
                Number = "CL234IR",
                Owner  = "James Doe",
                Route  = "Che Khotyn",
                Price  = "5",
                Train  = "red"
            });

            addCarToPoliceDatabase(factory, new Ticket
            {
                Number = "CL234IR",
                Owner  = "James Doe",
                Route  = "Che Khotyn",
                Price  = "1",
                Train  = "red"
            });

            factory.listFlyweights();
        }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            Console.WriteLine("+-----Design Patterns com C# - Flyweight-----+");
            Console.WriteLine();

            FlyweightFactory factory = new FlyweightFactory();

            string cor = string.Empty;

            Turtle turtle = null;

            while (true)
            {
                Console.WriteLine("---------------------------------------------------------------");
                Console.Write("Which turtle COLOR do you want to show on the screen? ");
                string color = Console.ReadLine();
                turtle = factory.GetTurtle(color);
                turtle.Show(color);
                Console.WriteLine(factory.FactorySituation());
            }
        }
Ejemplo n.º 29
0
        static void Main()
        {            
            int extrinsicstate = 22;

            FlyweightFactory factory = new FlyweightFactory();
            
            Flyweight fx = factory.GetFlyweight("X");
            fx.Operation(--extrinsicstate);

            Flyweight fy = factory.GetFlyweight("Y");
            fy.Operation(--extrinsicstate);

            Flyweight fz = factory.GetFlyweight("Z");
            fz.Operation(--extrinsicstate);

            UnsharedConcreteFlyweight fu = new UnsharedConcreteFlyweight();

            fu.Operation(--extrinsicstate);
            
            Console.ReadKey();
        }
Ejemplo n.º 30
0
        static void Main()
        {
            int brick = 10;

            FlyweightFactory factory = new FlyweightFactory();

            Flyweight fx = factory.GetFlyweight("X");
            fx.Operation(--brick);

            Flyweight fy = factory.GetFlyweight("Y");
            fy.Operation(--brick);

            Flyweight fz = factory.GetFlyweight("Z");
            fz.Operation(--brick);

            UnsharedBrickFlyweight fu = new UnsharedBrickFlyweight();

            fu.Operation(--brick);

            Console.ReadKey();
        }
Ejemplo n.º 31
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello Flyweight design pattern!");

            var serviceCollection = new ServiceCollection().AddMemoryCache().BuildServiceProvider();

            FlyweightFactory.cache = serviceCollection.GetService <IMemoryCache>();

            var countries = FlyweightFactory.GetCountries();

            // will be returned from Cache
            var countriesCalledFromOtherPlace = FlyweightFactory.GetCountries();

            Console.WriteLine("These countries will be returned from cache!");
            foreach (var item in countries)
            {
                Console.WriteLine($"Id: {item.Id} Name: {item.Name}");
            }

            Console.ReadKey();
        }
Ejemplo n.º 32
0
        static void Main()
        {
            int extrinsicstate = 22;

            var factory    = new FlyweightFactory();
            var flyweightA = factory.GetFlyweight("A");

            flyweightA.StatefulOperation(--extrinsicstate);

            var flyweightB = factory.GetFlyweight("B");

            flyweightB.StatefulOperation(--extrinsicstate);

            var flyweightC = factory.GetFlyweight("C");

            flyweightC.StatefulOperation(--extrinsicstate);

            var unsharedFlyweight = new UnsharedFlyweight();

            unsharedFlyweight.StatefulOperation(--extrinsicstate);
        }
Ejemplo n.º 33
0
        static void Main()
        {
            int brick = 10;

            FlyweightFactory factory = new FlyweightFactory();

            Flyweight fx = factory.GetFlyweight("X");

            fx.Operation(--brick);

            Flyweight fy = factory.GetFlyweight("Y");

            fy.Operation(--brick);

            Flyweight fz = factory.GetFlyweight("Z");

            fz.Operation(--brick);

            UnsharedBrickFlyweight fu = new UnsharedBrickFlyweight();

            fu.Operation(--brick);

            Console.ReadKey();
        }
Ejemplo n.º 34
0
        private static void Main()
        {
            var extrinsicstate = 100;

            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 unsharedConcreteFlyweight = new UnsharedConcreteFlyweight();

            unsharedConcreteFlyweight.Operation(--extrinsicstate);

            Console.ReadKey();
        }
Ejemplo n.º 35
0
        static void Main(string[] args)
        {
            #region 工厂方法
            double total = 0.0d;
            CashContext cc = new CashContext(new CashNormal());
            total = cc.GetResult(100.04);
            cc = new CashContext(new CashRebate("0.8"));
            total = cc.GetResult(100.04);
            Console.WriteLine(total);
            #endregion

            #region 装饰器方法
            Decorator.Component person = new Decorator.Component("xiaocai");

            Tshirt tshirt = new Tshirt();
            BigTrouser bt = new BigTrouser();

            bt.Decorator(person);
            tshirt.Decorator(bt);
            tshirt.show();

            Console.WriteLine("*****************************");
            #endregion

            #region 代理方法
            SchoolGirl sg = new SchoolGirl();
            sg.Name = "李娇骄";
            Proxy.Proxy daili = new Proxy.Proxy(sg);
            daili.GiveDolls();
            daili.GiveFlowers();
            #endregion

            #region 原型模式
            ConcretePrototype1 p1 = new ConcretePrototype1("123");
            ConcretePrototype1 c1 = (ConcretePrototype1)p1.Clone();
            Console.WriteLine("Cloned :"+c1.Id);

            Resume a = new Resume("Andy");
            a.setInfo("Man", "24");
            a.setWorkExperience("1998-2005","IBM ");
            Resume b = (Resume)a.Clone();
            b.setWorkExperience("2002-2005", "Dell");
            a.display();
            b.display();
            #endregion

            #region 模板模式
            Console.WriteLine("Student A testPaper:");
            TestPaperA testA = new TestPaperA();
            testA.Test1();
            testA.Test2();
            Console.WriteLine("Student B testPaper:");
            TestPaperB testB = new TestPaperB();
            testB.Test1();
            testB.Test2();
            #endregion

            #region 抽象工厂方法
            User user = new User();

            IFactory factory = new SqlServerFactory();
            IUser iu = factory.CreateUser();
            //IUser riu = (IUser)Assembly.Load("AbstractFactory").CreateInstance("SqlserverUser");
            //反射
            //Assembly.Load("程序集名称").CreateInstance("程序集名称.类名称");
            iu.Insert(user);
            iu.GetUser(1);
            #endregion

            #region Facade 外观模式
            Fund jijin = new Fund();
            jijin.BuyFund();
            jijin.sellFund();
            #endregion

            #region 建造者模式
            Director director = new Director();
            abstractBuilder builder1 = new Builder1();
            abstractBuilder builder2 = new BuilderB();
            director.Construct(builder1);
            Builder.Builder b1 = builder1.getBuilder();
            b1.show();

            director.Construct(builder2);
            Builder.Builder b2 = builder2.getBuilder();
            b2.show();
            #endregion
            #region 观察者模式
            Observer.ConcreteSubject s = new Observer.ConcreteSubject();
            s.Attach(new Observer.ConcreteObserver(s, "x"));
            s.Attach(new Observer.ConcreteObserver(s, "y"));
            s.SubjectState = "ABC";
            s.Notify();
            ///下面是使用委托
            ///委托就是一种引用方法的类型。一旦为委托分配了方法,委托将于该方法具有完全相同的行为。
            ///委托方法的使用可以像其他的方法一样具有参数和返回值。委托可以看作是对函数的抽象,是函数的”类“,委托的实例将代表一个具体的函数
            ///一个委托可以搭载多个方法,所有方法被依次唤起,委托搭载的方法不需要属于同一个类,只需要具有相同的原型和形式,也就是拥有相同的参数列表和返回类型。
            ///在使用带参数的委托时,只需要在声明事件的地方将参数传递给事件。在绑定时将调用的方法绑定给事件。
            Bosscs boss = new Bosscs();
            StockObserver tongshi1 = new StockObserver("tongshi1",boss);
            NBAObserver tongshiNBA = new NBAObserver("tongshiNBA", boss);
            boss.Update += new EventHandler1(tongshi1.CloseStockMarket);
            boss.Update += new EventHandler1(tongshiNBA.CloseStockMarket);
            boss.update2 += new EventHandler2(tongshiNBA.print);
            boss.SubjectState = " I am back ";
            boss.Notify();
            #endregion

            #region 状态模式
            State.Context c = new State.Context(new CreateStateA());
            c.Request();
            c.Request();
            c.Request();
            c.Request();

            #endregion

            #region 备忘录模式
            Originator o = new Originator();
            o.State = "On";
            o.Show();
            Caretaker care = new Caretaker();
            care.Memento = o.CreateMemento();
            o.State = "Off";
            o.Show();

            o.SetMemento(care.Memento);
            o.Show();

            GameRole gameRole = new GameRole();
            gameRole.GetInitState();
            gameRole.StateDisplay();

            RoleStateManager stateManager = new RoleStateManager();
            stateManager.Memento = gameRole.SaveState();

            gameRole.Fight();
            gameRole.StateDisplay();

            gameRole.RecoveryState(stateManager.Memento);
            gameRole.StateDisplay();
            #endregion

            #region 组合模式
            Composite.Composite root = new Composite.Component("root");
            root.Add(new Leaf("Leaf A"));
            root.Add(new Leaf("Leaf B"));

            Composite.Composite comp = new Composite.Component("comp X");
            comp.Add(new Leaf("Leaf XA"));
            comp.Add(new Leaf("Leaf XB"));
            root.Add(comp);

            Composite.Composite comp2 = new Composite.Component("Comp X2");
            comp2.Add(new Leaf("Leaf X2A"));
            comp2.Add(new Leaf("Leaf X2B"));
            comp.Add(comp2);

            root.Add(new Leaf("Leaf C"));
            Leaf leaf = new Leaf("Leaf D");

            root.Add(leaf);
            root.Display(1);
            root.Remove(leaf);
            root.Display(1);
            #endregion

            #region 迭代器模式
            ConCreteAggregate aggregate = new ConCreteAggregate();
            aggregate[0] = "大鸟";
            aggregate[1] = "小菜";
            aggregate[2]="行李";
            aggregate[3] = "老外";
            aggregate[4] = "小偷";
            Iterator.Iterator myIterator = new ConCreteIterator(aggregate);
            object item = myIterator.First();
            while (!myIterator.IsDone())
            {
                Console.WriteLine(myIterator.CurrentItem() + "请买车票");
                myIterator.Next();
            }
            #endregion

            #region 单例模式
             //所有类都有构造方法,不编码则默认生成空的构造方法,若有显示定义的构造方法,默认的构造方法就会失效。只要将构造方法改写为私有的,外部的程序就不能通过new 来初始化它。
            //通过一个共有的方法来返回类的实例。
            Singleton.Singleton s1 = Singleton.Singleton.GetInstance();
            Singleton.Singleton s2 = Singleton.Singleton.GetInstance();

            if (s1 == s2)
            {
                Console.WriteLine("两个对象是相同的实例。");
            }

            #endregion

            #region 命令模式
            Receiver r = new Receiver();
            Command.Command command = new Command.ConcreteCommand(r);
            Invoker invoker = new Invoker();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            #endregion

            #region 职责链模式
            Handler h1 = new ConcreteHandler1();
            Handler h2 = new ConcreteHandler2();
            h1.SetSuccessor(h2);
            int[] requests = { 2, 3, 4, 5, 6, 12, 34, 11, 15 };
            foreach (int request in requests)
            {
                h1.HandlerRequest(request);
            }
            #endregion

            #region 中介者模式
            ConcreteMediator mediator = new ConcreteMediator();
            ConcreteColleague1 colleague1 = new ConcreteColleague1(mediator);
            ConcreteColleague2 colleague2 = new ConcreteColleague2(mediator);
            mediator.Colleague1 = colleague1;
            mediator.Colleague2 = colleague2;
            colleague1.Send("吃饭了吗?");
            colleague2.Send("还没有呢");
            #endregion

            #region 享元模式
            int extri = 22;
            FlyweightFactory f = new FlyweightFactory();
            Flyweight.Flyweight fx = f.GetFlyweight("X");
            fx.Operation(--extri);

            Flyweight.Flyweight fy = f.GetFlyweight("Y");
            fy.Operation(--extri);

            Flyweight.Flyweight fz = f.GetFlyweight("Z");
            fz.Operation(--extri);

            #endregion

            #region 解释器模式
            <<<<<<< HEAD
            Interpreter.Context context = new Interpreter.Context();
            IList<Interpreter.AbstractExpression> list = new List<Interpreter.AbstractExpression>();
            list.Add(new Interpreter.TerminalExpression());
            list.Add(new Interpreter.NormalExpression());
            foreach (Interpreter.AbstractExpression exp in list)
                exp.Interpret(context);
            =======
            Interpreter.Context context1 = new Interpreter.Context();
            IList<AbstractExpression> list = new List<AbstractExpression>();
            list.Add(new TerminalExpression());
            list.Add(new NonTerminalExpression());
            foreach (AbstractExpression exp in list)
            {
                exp.Interpreter(context1);
            }
            #endregion

            #region 访问者模式
            ObjectStructure os = new ObjectStructure();
            os.Add(new Man());
            os.Add(new Woman());
            Success v1 = new Success();
            os.Display(v1);
            Failing f1 = new Failing();
            os.Display(f1);

            Amativeness a1 = new Amativeness();
            os.Display(a1);
            >>>>>>> 77e342ef6e96917a8dc01e72e41626dcffd4ba13
            #endregion
            Console.Read();
        }