static void Main(string[] args)
        {
            ICarSupplier objCarSupplier = CarFactory.GetCarInstance(2);

            objCarSupplier.GetCarModel();
            Console.WriteLine("And Coloar is " + objCarSupplier.CarColor);

            Console.ReadLine();
        }
예제 #2
0
        /// <summary>
        /// Acts as the client in the Proxy Pattern
        /// </summary>
        private static void ProxyPattern()
        {
            Console.WriteLine("===== Proxy Pattern Example =====");

            Console.WriteLine("Starting the car as a buyer.");
            ICar boughtCar = CarFactory.GetCar(DriverType.Buyer);       // Returns a proxy

            boughtCar.Start();                                          // Car starts (passes security check in the proxy)

            Console.WriteLine("Starting the car as a demo driver.");
            ICar demoCar = CarFactory.GetCar(DriverType.Demo);          // Returns a subject

            demoCar.Start();                                            // Car starts (the subject does not have a security check)

            Console.WriteLine("Starting the car as a theft.");
            ICar stolenCar = CarFactory.GetCar(DriverType.Theft);       // Returns a proxy

            stolenCar.Start();                                          // Car does not start (fails security check in the proxy)

            Console.WriteLine();
        }
예제 #3
0
        /// <summary>
        /// Client
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            var superBuilder    = new SuperCarBuilder();
            var notSuperBuilder = new NotSoSuperCarBuilder();
            var factory         = new CarFactory();
            var builders        = new List <CarBuilder>
            {
                superBuilder, notSuperBuilder
            };

            foreach (var bld in builders)
            {
                var c = factory.Build(bld);
                Console.WriteLine($"The car requested by {bld.GetType().Name}: " +
                                  $"\n------------------" +
                                  $"\n Horse power: {c.HorsePower}" +
                                  $"\n Impressive feature: {c.MostImpressiveFeature}" +
                                  $"\n Top Speed: {c.TopSpeedMPH} mph\n");
            }

            Console.ReadLine();
        }
예제 #4
0
        static void Main(string[] args)
        {
            #region Decorator - Using Composition to limit inheritance and simplify object relationships easier to maintain and manage.
            //Inside ConcreteDecorator any number of features can be added to the car and price for the car can be updated.
            Decorator.Component.Car sampleCar = new CompactCar();
            sampleCar = new LeatherSeats(sampleCar);
            Console.WriteLine(sampleCar.GetDescription());
            Console.WriteLine($"{sampleCar.GetCarPrice():C2}");
            #endregion

            #region Observer - Change in one object causes a change or action in another.
            var trump     = new Trump("I love my wife");
            var firstFan  = new Fan("Rohit");
            var secondFan = new Fan("Ram");
            trump.AddFollower(firstFan);
            trump.AddFollower(secondFan);
            trump.Tweet = "I hate media";
            #endregion

            #region Builder Pattern- Separate and reuse a specific process to build an object /use when constructing a complex object
            //Director- construct ()
            //Builder - Build part
            //CarBuilder to construct two types of cars
            //override the method of building a car in separate classes which derive from an abstract carbuilder
            //create a list of carbuilder objects to specify the current known types of cars that can be built
            //create a factory
            var superBuilder       = new SuperCarBuilder();
            var notSoSsuperBuilder = new NotSoSuperCarBuilder();

            var factory  = new CarFactory();
            var builders = new List <CarBuilder> {
                superBuilder, notSoSsuperBuilder
            };

            foreach (var b in builders)
            {
                var c = factory.Build(b);
                Console.WriteLine($"The car requested by " + $"{b.GetType().Name}:" + Environment.NewLine
                                  + $"Horse Power: {c.HorsePower}" + Environment.NewLine
                                  + $"Impressive feature: {c.MostImpressiveFeature}" + Environment.NewLine
                                  + $"Top speed: {c.TopSpeedMPH} mph" + Environment.NewLine);
            }
            #endregion

            #region Bridge Pattern- Used to separate an abstraction from its implementation so both can be modified independently
            //Sending messages from sms or service without each affecting the other
            IMessageSender text = new TextSender();
            IMessageSender web  = new WebServiceSender();

            Message message = new SystemMessage(text);
            message.Subject       = "A message";
            message.Body          = "hi there, please know this";
            message.MessageSender = text;
            message.Send();

            message.MessageSender = web;
            message.Send();

            #endregion

            #region Chain of responsibility- Chain the receiving objects and pass the request along the chain until an object handles it.
            //Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request
            Approver Bobby  = new Director();
            Approver Sunny  = new VicePresident();
            Approver Dharam = new President();

            Bobby.SetSuccessor(Sunny);
            Sunny.SetSuccessor(Dharam);

            Purchase P = new Purchase()
            {
                Amount = 10000, Number = 1
            };
            Bobby.ProcessRequest(P);


            #endregion

            #region Command - Wrap request as an object to be implemented later or invoke at different points in time.
            //Encapsulate a request as an object, thereby letting you parameterize clients with different requests -queue or log  and support undoable operations
            //Use an object to store required information to perform an action at any point in time.
            var user = new User();
            user.Compute('+', 100);
            user.Compute('-', 50);
            user.Compute('*', 10);
            user.Compute('/', 2);

            //undo
            user.Undo(4);

            //Redo
            user.Redo(3);
            #endregion
            Console.ReadLine();
        }
예제 #5
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
        }