Exemplo n.º 1
0
        internal static void Command()
        {
            Console.WriteLine("Command pattern demo");
            Console.WriteLine("------------------------------------");

            var modifyPrice = new ModifyPrice();
            var product     = new Product("IPhone", 25000);

            var productCommand = new ProductCommand(product, PriceAction.Increase, 1000);

            modifyPrice.SetCommand(productCommand);
            modifyPrice.Invoke();
            Console.WriteLine(product);

            var productCommand2 = new ProductCommand(product, PriceAction.Decrease, 500);

            modifyPrice.SetCommand(productCommand2);
            modifyPrice.Invoke();

            Console.WriteLine(product);
            modifyPrice.Undo();
            Console.WriteLine(product);

            Console.WriteLine("");
            Console.WriteLine("------------------------------------");
            Console.WriteLine("Command pattern demo 2");
            Console.WriteLine("------------------------------------");

            var bank = new BankAccount();
            var cmd  = new BankCommand();

            bank.Balance = 90000;
            Console.WriteLine($"Balance: {bank.Balance}");

            cmd.Amount = 1000;
            Console.WriteLine($"Deposit: {cmd.Amount}");
            cmd.BalanceAction = _4_Behavioral_Patterns.Command.Demo2.Action.Deposit;
            bank.Execute(cmd);

            cmd.Amount = 2000;
            Console.WriteLine($"Deposit: {cmd.Amount}");
            cmd.BalanceAction = _4_Behavioral_Patterns.Command.Demo2.Action.Deposit;
            bank.Execute(cmd);

            cmd.Amount = 8000;
            Console.WriteLine($"Withdraw: {cmd.Amount}");
            cmd.BalanceAction = _4_Behavioral_Patterns.Command.Demo2.Action.Withdraw;
            bank.Execute(cmd);

            cmd.Amount = 100000;
            Console.WriteLine($"Withdraw: {cmd.Amount}");
            cmd.BalanceAction = _4_Behavioral_Patterns.Command.Demo2.Action.Withdraw;
            bank.Execute(cmd);

            Console.WriteLine($"Balance: {bank.Balance}");
        }
Exemplo n.º 2
0
        public void Should_Decrease_Price()
        {
            ModifyPrice modifyPriceInvolker = new ModifyPrice();
            var         product             = new Product("Phone", 500);

            modifyPriceInvolker.AddCommand(new ProductCommand(product, PriceAction.Decrease, 100));
            modifyPriceInvolker.AddCommand(new ProductCommand(product, PriceAction.Decrease, 200));

            modifyPriceInvolker.Invoke();

            product.ToString().Should().Be("Current price for the Phone product is 200$.");
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            var modifyPrice = new ModifyPrice();
            var product     = new Product("Phone", 500);

            Execute(product, modifyPrice, new ProductCommand(product, PriceAction.Increase, 100));

            Execute(product, modifyPrice, new ProductCommand(product, PriceAction.Increase, 50));

            Execute(product, modifyPrice, new ProductCommand(product, PriceAction.Increase, 25));

            Console.WriteLine(product);
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            var random = new Random();

            // ********* Builder(Fluent) Pattern Usage: START *********

            // creating dummy data for products simulation
            int capacity = 3;
            var products = new List <Product>(capacity);

            for (int i = 1; i <= capacity; i++)
            {
                products.Add(
                    new Product
                {
                    Id            = Guid.NewGuid(),
                    Name          = $"Product {i}",
                    Price         = Math.Round(random.NextDouble() * 100, 2),
                    NumberInStock = random.Next(100)
                });
            }

            // creation of builder is mandatory. because we use it when we create manager for report builder
            var builder = new ProductStockReportBuilder(products);
            var manager = new ProductStockReportManager(builder);

            // report is generated by manager
            manager.BuildReport();

            var productsReport = builder.GetReport();

            Console.WriteLine(productsReport);

            // ********* Builder(Fluent) Pattern Usage: END *********

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

            // ********* Fluent Builder Interface with Recursive Generics Pattern Usage: START *********

            var emp = EmployeeBuilderManager.NewEmployee
                      .WithFirstName("Nuran").WithLastName("Tarlan").WithAge(18)
                      .WithEMail("*****@*****.**")
                      .WithMainPhone("xxx-xxx-xx-xx").WithBackupPhone("xxx-xxx-xx-xx")
                      .AtPosition(Positions.FullStackDeveloper).WithSalary(500).Build();

            Console.WriteLine(emp);

            // ********* Fluent Builder Interface with Recursive Generics Pattern Usage: END *********

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

            // ********* Faceted Builder Pattern Usage: START

            var car = new CarBuilderFacade()
                      .Info.WithBrand(CarBrands.Subaru).WithModel("Impreza").CreatedAt(2003).WithDistance(186522.5)
                      .Engine.WithEngine(1800).WithHorsePower(422).WithTorque(600)
                      .Trade.WithPrice(18000.0m).IsSecondHand(true)
                      .Address.InCity("Baku").InDealer("Subaru XXXXX-XX")
                      .Build();

            Console.WriteLine(car);

            // ********* Faceted Builder Pattern Usage: END

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

            // ********* Factory Method Pattern Usage: START

            AirConditioner.InitializeFactories()
            .ExecuteCreation(Actions.Cooling, 20.2)
            .Operate();

            // ********* Factory Method Pattern Usage: END

            // -------------------------------------------------------------------------
            Console.WriteLine("\n-------------------------------\n");

            // ********* Singleton Pattern Usage: START

            var db1 = SingletonDataContainer.GetInstance;

            Console.WriteLine($"Population of Sumqayit: {db1.GetPopulation("Sumqayit")}");

            var db2 = SingletonDataContainer.GetInstance;

            Console.WriteLine($"Baku: {db2.GetPopulation("Baku")} people");

            // ********* Singleton Pattern Usage: END

            // -------------------------------------------------------------------------
            Console.WriteLine("\n-------------------------------\n");

            // ********* Adapter Pattern Usage: START

            var xmlConverter = new CustomXmlConverter();
            var adapter      = new XmlToJsonAdapter(xmlConverter);

            adapter.ConvertXmlToJson();

            // ********* Adapter Pattern Usage: END

            // -------------------------------------------------------------------------
            Console.WriteLine("\n-------------------------------\n");

            // ********* Composite Pattern Usage: START

            // single gift
            var phone = new SingleGift("Phone", 500);

            phone.CalculateTotalPrice();
            Console.WriteLine();

            // composite many gifts together
            var rootBox  = new CompositeGift("Surprise Box for Teenagers", true);
            var truckToy = new SingleGift("Truck Toy", 220);
            var plainToy = new SingleGift("Plain Toy", 89);

            rootBox.Add(truckToy);
            rootBox.Add(plainToy);

            var childBox   = new CompositeGift("Surprise Box for Children", false);
            var soldierToy = new SingleGift("Soldier Toy", 15);

            childBox.Add(soldierToy);
            rootBox.Add(childBox);

            rootBox.CalculateTotalPrice();

            // ********* Composite Pattern Usage: END

            // -------------------------------------------------------------------------
            Console.WriteLine("\n-------------------------------\n");

            // ********* Decorator Pattern Usage: START

            var regularOrder = new RegularOrder();

            Console.WriteLine(regularOrder.CalculateTotalOrderPrice() + "\n");

            var preOrder = new PreOrder();

            Console.WriteLine(preOrder.CalculateTotalOrderPrice() + "\n");

            var premiumPreOrder = new PremiumPreOrder(preOrder);

            Console.WriteLine(premiumPreOrder.CalculateTotalOrderPrice());

            // ********* Decorator Pattern Usage: END

            // -------------------------------------------------------------------------
            Console.WriteLine("\n-------------------------------\n");

            // ********* Command Pattern Usage: START

            var modifyPrice = new ModifyPrice();
            var product     = new Product2("Phone", 500);

            modifyPrice.Execute(new ProductCommand(product, PriceAction.Increase, 100));
            modifyPrice.Execute(new ProductCommand(product, PriceAction.Decrease, 700));
            modifyPrice.Execute(new ProductCommand(product, PriceAction.Decrease, 20));

            Console.WriteLine(product);
            modifyPrice.UndoActions();
            Console.WriteLine(product);

            // ********* Command Pattern Usage: END

            // -------------------------------------------------------------------------
            Console.WriteLine("\n-------------------------------\n");

            // ********* Strategy Pattern Usage: START

            var reports = new List <DeveloperReport>
            {
                new DeveloperReport {
                    Id = 1, Name = "Dev1", Level = DeveloperLevel.Senior, HourlyRate = 30.5, WorkingHours = 160
                },
                new DeveloperReport {
                    Id = 2, Name = "Dev2", Level = DeveloperLevel.Junior, HourlyRate = 20, WorkingHours = 120
                },
                new DeveloperReport {
                    Id = 3, Name = "Dev3", Level = DeveloperLevel.Senior, HourlyRate = 32.5, WorkingHours = 130
                },
                new DeveloperReport {
                    Id = 4, Name = "Dev4", Level = DeveloperLevel.Junior, HourlyRate = 24.5, WorkingHours = 140
                }
            };
            var calculatorContext = new SalaryCalculator(new JuniorDeveloperSalaryCalculator());
            var juniorTotal       = calculatorContext.Calculate(reports);

            Console.WriteLine($"Total amount for junior salaries is: {juniorTotal}");
            calculatorContext.SetCalculator(new SeniorDeveloperSalaryCalculator());
            var seniorTotal = calculatorContext.Calculate(reports);

            Console.WriteLine($"Total amount for senior salaries is: {seniorTotal}");
            Console.WriteLine($"Total cost for all the salaries is: {juniorTotal + seniorTotal}");

            // ********* Strategy Pattern Usage: END

            // -------------------------------------------------------------------------
            Console.WriteLine("\n-------------------------------\n");

            // ********* Facade Pattern Usage: START

            var facade = new Facade.Facade();

            var chickenOrder = new Order()
            {
                DishName = "Chicken with rice", DishPrice = 20.0, User = "******", ShippingAddress = "Random street 123"
            };
            var sushiOrder = new Order()
            {
                DishName = "Sushi", DishPrice = 52.0, User = "******", ShippingAddress = "More random street 321"
            };

            facade.OrderFood(new List <Order> {
                chickenOrder, sushiOrder
            });

            // ********* Facade Pattern Usage: END

            // -------------------------------------------------------------------------
            Console.WriteLine("\n-------------------------------\n");

            // ********* Prototype Pattern Usage: START

            var grid = new List <IBlock>();

            grid.AddRange(new List <IBlock>
            {
                BlockFactory.Create("Hello, world!"),
                BlockFactory.Create("3"),
                BlockFactory.Create("16/05/2002"), // datetime
                BlockFactory.Create("08/22/2021")  // string, because 12 month exist in calendar
            });

            foreach (var block in grid)
            {
                Console.WriteLine(block);
            }

            var block5 = (DateTimeBlock)grid[2].Clone();

            block5.Format = "MM/dd/yyyy";
            grid.Add(block5);
            Console.WriteLine("\nblock5 is added...");
            Console.WriteLine(block5);

            var block6 = (DateTimeBlock)grid[4].Clone();

            block6.DateTime = DateTime.UtcNow;
            grid.Add(block6);
            Console.WriteLine("\nblock6 is added...");
            Console.WriteLine(block6);

            // ********* Prototype Pattern Usage: END

            // -------------------------------------------------------------------------
            Console.WriteLine("\n-------------------------------\n");

            // ********* Protection-Proxy Pattern Usage: START

            var settings = new Settings("settings config");

            Console.WriteLine(settings.GetConfig());

            var authService       = new AuthService();
            var protectedSettings = new ProtectedSettings(authService);

            Console.WriteLine(protectedSettings.GetConfig());

            // ********* Protection-Proxy Pattern Usage: END

            // ********* Iterator Pattern Usage: START

            var numbers = new CustomLinkedList <int>(1);

            for (int i = 2; i < 8; i++)
            {
                numbers.Add(i);
            }

            var iterator = numbers.Iterator;

            while (!iterator.Complete)
            {
                Console.WriteLine(iterator.Next());
            }

            // Exception will be thrown
            // Console.WriteLine(iterator.Next());

            // ********* Iterator Pattern Usage: END
        }
Exemplo n.º 5
0
 public static void Execute(Product product, ModifyPrice modifyPrice, ICommand productCommand)
 {
     modifyPrice.SetCommand(productCommand);
     modifyPrice.Invoke();
 }
Exemplo n.º 6
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
        }