Ejemplo n.º 1
0
        static void Invock15()
        {
            var root = new Composite("root");

            root.Add(new Leaf("Leaf A"));
            root.Add(new Leaf("Leaf B"));

            var comp1 = new Composite("Composite1");

            comp1.Add(new Leaf("Composite1 Leaf A"));
            comp1.Add(new Leaf("Composite1 Leaf B"));
            root.Add(comp1);

            var comp2 = new Composite("Composite2");

            comp2.Add(new Leaf("Composite2 Leaf A"));
            comp2.Add(new Leaf("Composite2 Leaf B"));
            comp1.Add(comp2);

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

            root.Display();
        }
Ejemplo n.º 2
0
        public static void Main()
        {
            //--------------------------- AbstractFactory
            Console.WriteLine("--------------------------- AbstractFactory");

            Client client = null;

            client = new Client(new CocaColaFactory());
            client.Run();

            client = null;
            client = new Client(new PepsiColaFactory());
            client.Run();

            /*
             *  AbstractFactory.Program + CocaColaBottle interacts with AbstractFactory.Program + CocaColaWater
             *  AbstractFactory.Program + CocaColaCover closes AbstractFactory.Program + CocaColaBottle
             *  AbstractFactory.Program + PepsiColaBottle interacts with AbstractFactory.Program + PepsiColaWater
             *  AbstractFactory.Program + PepsiColaCover closes AbstractFactory.Program + PepsiColaBottle
             */


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

            Builder  stoneHouseBuilder = new ConcreteBuilder();
            Director director          = new Director(stoneHouseBuilder);

            director.Construct();

            House house = stoneHouseBuilder.GetResult();

            house.Show();

            /*
             *  Basement Created
             *  Floor Created
             *  Roof Created
             *  Element: DesignPatterns.Basement builded.
             *  Element: DesignPatterns.Floor builded.
             *  Element: DesignPatterns.Roof builded.
             */


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

            Creator creator = new ConcreteCreator();
            Product product = null;

            product = creator.FactoryMethod();
            //creator.AnOperation();

            /* 46104728 */

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

            Prototype prototype = new ConcretePrototype1(1);
            Prototype clone     = prototype.Clone();

            clone.AnOperation();

            Prototype prototype2 = new ConcretePrototype2(2);
            Prototype clone2     = prototype2.Clone();

            clone2.AnOperation();

            /*
             *  ID : 1
             *  Class : DesignPatterns.ConcretePrototype1
             *  ID : 2
             *  Class : DesignPatterns.ConcretePrototype2
             */


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

            Singleton firstInstance  = Singleton.Instance();
            Singleton secondInstance = Singleton.Instance();

            // Singleton thirdinstance = new Singleton(); // error

            Console.WriteLine(firstInstance.GetHashCode());
            Console.WriteLine(secondInstance.GetHashCode());
            Console.WriteLine(ReferenceEquals(firstInstance, secondInstance));

            firstInstance.SampleOperation();
            Console.WriteLine(secondInstance.GetSampleData());

            /*
             *  12289376
             *  12289376
             *  True
             *  Singleton Sample Data
             */


            //Console.WriteLine("--------------------------- Adapter (Class)");
            //iTarget target = new Adapter();
            //target.Operation();

            Console.WriteLine("--------------------------- Adapter (Object)");
            Target target = new Adapter();

            target.Operation();

            /*
             *  SpecificOperation
             */


            //--------------------------- Bridge
            Console.WriteLine("--------------------------- Bridge");
            Abstract AnotherAbs11 = new RefinedAbstract1(new ConcreteImp1());

            Console.WriteLine(AnotherAbs11.DoSomething());

            Abstract AnotherAbs21 = new RefinedAbstract2(new ConcreteImp1());

            Console.WriteLine(AnotherAbs21.DoSomething());

            Abstract AnotherAbs12 = new RefinedAbstract1(new ConcreteImp2());

            Console.WriteLine(AnotherAbs12.DoSomething());

            Abstract AnotherAbs22 = new RefinedAbstract2(new ConcreteImp2());

            Console.WriteLine(AnotherAbs22.DoSomething());

            /*
             *  RefinedAbstract1 is doing smth. with Imp1
             *  RefinedAbstract2 is doing different things with Imp1
             *  RefinedAbstract1 is doing smth. with Imp2
             *  RefinedAbstract2 is doing different things with Imp2
             */

            //--------------------------- Composite
            Console.WriteLine("--------------------------- Composite");
            Component root    = new Composite("root");
            Component branch1 = new Composite(" - branch1");
            Component branch2 = new Composite(" - branch2");
            Component leaf1   = new Leaf(" - - leaf1");
            Component leaf2   = new Leaf(" - - leaf2");
            Component leaf3   = new Leaf(" - - leaf3");

            root.Add(branch1);
            root.Add(branch2);
            branch1.Add(leaf1);
            branch1.Add(leaf2);
            branch2.Add(leaf3);

            root.Operation();

            /*
             *  root
             *   - branch1
             *   - - leaf1
             *   - - leaf2
             *   - branch2
             *   - - leaf3
             */


            //--------------------------- Decorator
            Console.WriteLine("--------------------------- Decorator");
            AbstractComponent someComponenet = new ConcreteComponenet();
            Decorator         decoratorA     = new ConcreteDecoratorA();
            Decorator         decoratorB     = new ConcreteDecoratorB();

            decoratorA.component = someComponenet;
            decoratorB.component = decoratorA;
            decoratorB.Operation();


            /*
             *  Concrete Componenet Operation
             *  Some State
             *  Some Behavior
             */


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

            facade.OperationAB();
            facade.OperationCD();

            /*
             *  Operation A
             *  Operation B
             *  Operation C
             *  Operation D
             */


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

            /*
             *  int externalState = 0;
             *
             *  Flyweight flyweight = null;
             *  FlyweightFactory factory = new FlyweightFactory();
             *
             *  flyweight = factory.GetFlyweight("1");
             *  flyweight.Operation(externalState);
             *
             *  flyweight = factory.GetFlyweight("10");
             *  flyweight.Operation(externalState);
             *
             *  flyweight = new UnsharedConcreteFlyweight();
             *  flyweight.Operation(externalState);
             */

            ActorMikeMyers mike = new ActorMikeMyers();

            RoleAustinPowers austin = new RoleAustinPowers(mike);

            austin.Greetings("Hello! I'm Austin Powers!");

            RoleDoctorEvil dr = new RoleDoctorEvil(mike);

            dr.Greetings("Hello! I'm Dr. Evil!");

            /*
             *  Hello! I'm Austin Powers!
             *  Hello! I'm Dr. Evil!
             */


            //--------------------------- Proxy
            Console.WriteLine("--------------------------- Proxy");
            //Subject original = new Original();
            //Subject proxy = new Proxy(original);
            //proxy.Operation();

            Subject anotherProxy = new Proxy();

            anotherProxy.Operation();

            /*
             *  Do Smth
             *  Do Smth
             */


            //--------------------------- ChainOfResponsibility
            Console.WriteLine("--------------------------- ChainOfResponsibility");
            Handler concreteHandler1 = new ConcreteHandler1();
            Handler concreteHandler2 = new ConcreteHandler2();

            concreteHandler1.successor = concreteHandler2;
            concreteHandler1.Operation(1);
            concreteHandler1.Operation(2);

            /*
             *  One
             *  Two
             */


            //--------------------------- Command
            Console.WriteLine("--------------------------- Command");
            Receiver povar = new Receiver();
            Command  zakaz = new ConcreteCommand(povar);
            //Invoker ofichiant = new Invoker(zakaz);
            Invoker ofichiant = new Invoker();

            ofichiant.StoreCommand(zakaz);
            ofichiant.Execute();

            /*
             *  Receiver!
             */


            //--------------------------- Interpreteur
            Console.WriteLine("--------------------------- Interpreteur");
            Context context = new Context
            {
                Vocabulary = 'a',
                Source     = "aaa"
            };

            var expression = new NonTerminalExpression();

            expression.Interpret(context);
            Console.WriteLine(context.Result);

            /*
             *  True
             */

            Console.ReadKey();
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            #region Creational Patterns
            //Singleton
            Singleton singleton = Singleton.GetInstance();
            singleton.someUsefulCode();

            Separate();

            //Builder
            Item ciastko = new ItemBuilder(0).SetName("Ciastko").SetType("Food").build();
            Console.WriteLine($"{ciastko.id}. {ciastko.name}, {ciastko.type}");

            Separate();

            //Prototype
            Person person      = new Person(1, 15, "John");
            Person shallowCopy = (Person)person.ShallowCopy();
            Person deepCopy    = (Person)person.DeepCopy();
            Console.WriteLine(person);
            Console.WriteLine(shallowCopy);
            Console.WriteLine(deepCopy);
            person.name = "Max";
            person.age  = 20;
            person.id   = new IdInfo(99);
            Console.WriteLine(person);
            Console.WriteLine(shallowCopy);
            Console.WriteLine(deepCopy);

            Separate();

            //AbstractFactory
            Car miniCar = CarFactory.CarBuilder(CarType.MINI);
            Car lumiCar = CarFactory.CarBuilder(CarType.LUXURY);

            Separate();

            //FactoryPattern
            ShapeFactory shapeFactory = new ShapeFactory();
            Shape        circle       = shapeFactory.GetShape("circle");
            circle.print();

            Separate();

            //ObjectPool
            SomeObject so1 = Pool.GetObject();
            SomeObject so2 = Pool.GetObject();
            Pool.ReleaseObject(so1);
            SomeObject so3 = Pool.GetObject();
            Console.WriteLine($"so1: {so1}");
            Console.WriteLine($"so2: {so2}");
            Console.WriteLine($"so3: {so3}");

            Separate();

            #endregion

            #region Structural Patterns

            //Adapter
            OldClass oldClass = new OldClass();
            IWrite   write    = new Adapter(oldClass);
            write.PrintMessage();

            Separate();

            //Bridge
            Thing triangle = new Ball(new Blue());
            triangle.print();

            Separate();

            //Composite
            Component leaf1 = new Leaf("leaf1");
            Component leaf2 = new Leaf("leaf2");
            Component leaf3 = new Leaf("leaf3");

            Component branch1 = new Composite("branch1");
            branch1.Add(leaf1);
            branch1.Add(leaf2);

            Component root = new Composite("root");
            root.Add(branch1);
            root.Add(leaf3);

            root.Display(1);

            Separate();

            //Decorator
            Weapon weapon = new BaseWeapon();
            weapon.shot();
            Weapon modifiedWeapon = new Stock(weapon);
            modifiedWeapon.shot();

            Separate();

            //Facade
            Student student = new Student();
            student.StartLearning();
            student.EndLearning();

            Separate();

            //Flyweight
            Particle p1 = ParticleFactory.getSmallParticle("red");  //new key
            Particle p2 = ParticleFactory.getSmallParticle("red");  //no new one
            Particle p3 = ParticleFactory.getSmallParticle("blue"); //new key

            Separate();

            //Proxy
            IBank proxyBank = new ProxyBank();
            proxyBank.Pay();

            Separate();

            #endregion

            #region Behavioral Patterns

            //ChainOfResponsibility
            Chain chain = new Chain();
            chain.Process(5);

            Separate();

            //Command
            var modifyPrice = new ModifyPrice();
            var product     = new Product("Brick", 200);

            Console.WriteLine(product);
            modifyPrice.SetCommandAndInvoke(new ProductCommand(product, PriceAction.Increase, 50));
            Console.WriteLine(product);

            Separate();


            //Iterator
            CarRepository carRepository = new CarRepository(new string[] { "Renault", "BMW", "VW" });

            for (IIterator i = carRepository.GetIterator(); i.hasNext();)
            {
                Console.WriteLine($"Car: {i.next()}");
            }

            Separate();

            //Mediator
            Mediator mediator = new RealMediator();
            APerson  jhon     = new RealPerson(mediator, "Jhon");
            APerson  max      = new RealPerson(mediator, "Max");
            APerson  emma     = new RealPerson(mediator, "Emma");
            mediator.AddPerson(jhon);
            mediator.AddPerson(max);
            mediator.AddPerson(emma);

            jhon.Send("I'm a jhon and this is my message! ");
            emma.Send("henlo");

            Separate();

            //Memento
            Localization         localization = new Localization("NY", 123, 111);
            LocalizationSnapshot snapshot     = localization.CreateSnapshot();
            Console.WriteLine(localization);

            localization.City = "Berlin";
            localization.X    = 999;
            Console.WriteLine(localization);

            snapshot.Restore();
            Console.WriteLine(localization);

            Separate();

            //Observer
            Customer james   = new Customer("James");
            Customer william = new Customer("William");
            Customer evelyn  = new Customer("Evelyn");

            Shop grocery = new Shop("YourFood");
            Shop DIYshop = new Shop("Tooler");

            grocery.AddSubscriber(james);
            grocery.AddSubscriber(william);
            grocery.AddSubscriber(evelyn);

            DIYshop.AddSubscriber(james);
            DIYshop.AddSubscriber(william);

            grocery.AddMerchandise(new Merchandise("pizza", 19));
            DIYshop.AddMerchandise(new Merchandise("hammer", 399));

            Separate();

            //State
            AudioPlayer ap = new AudioPlayer();
            ap.ClickPlay();
            ap.ClickLock();
            ap.ClickPlay();
            ap.ClickPlay();
            ap.ClickPlay();
            ap.ClickLock();
            ap.NextSong();
            ap.PreviousSong();

            Separate();

            //Strategy
            Calculator calculator = new Calculator(new AddingStrategy());
            calculator.Calculate(5, 2);
            calculator.ChangeStrategy(new SubtractingStrategy());
            calculator.Calculate(5, 2);

            Separate();

            //TemplateMethod
            Algorithm a1 = new AlgorithmWithStep2();
            a1.Execute();
            Algorithm a2 = new AlgorithmWithStep2and3();
            a2.Execute();

            Separate();

            //Visitor
            ElementA ea = new ElementA("ElementA");
            ElementA eb = new ElementA("ElementB");
            Visitor1 v1 = new Visitor1();
            Visitor2 v2 = new Visitor2();
            ea.Accept(v1);
            ea.Accept(v2);
            eb.Accept(v1);
            eb.Accept(v2);
            #endregion
        }