Example #1
0
        static void Main(string[] args)
        {
            var container = ContainerConfig.Configure();

            Console.WriteLine("\n1- SimpleFactory");

            //1 - SimpleFactory
            var simpleFactoryClient = new SimpleFactoryClient();

            simpleFactoryClient.BuildPizza(typeof(NeapolitanPizza).Name);

            Console.WriteLine("\n2- FactoryMethod");

            //2 - FactoryMethod

            using (var scope = container.BeginLifetimeScope())
            {
                var factory             = scope.Resolve <FactoryMethodPizzaFactory>();
                var factoryMethodClient = new FactoryMethodClient(factory);
                factoryMethodClient.BuildPizza();
            }

            Console.WriteLine("\n3 - AbstractFactory");

            //3 - AbstractFactory
            using (var scope = container.BeginLifetimeScope())
            {
                var factory             = scope.ResolveNamed <AbstractFactoryPizzaFactory>(typeof(NeapolitanPizzaThickCrustFactory).Name);
                var factoryMethodClient = new AbstractFactoryClient(factory);
                factoryMethodClient.BuildPizza();
            }

            Console.ReadLine();
        }
Example #2
0
        static void Main(string[] args)
        {
            Console.WriteLine("----------------------------- Abstract Factory -----------------------------");
            AbstractFactoryClient abstractFactoryClient = new AbstractFactoryClient(new WinFactory()); // change to MacFactory if needed

            abstractFactoryClient.Start();

            Console.WriteLine("----------------------------- Factory Method -----------------------------");
            Parent.Create().Run();
            Parent.Create().Run();

            Console.WriteLine("----------------------------- Adapter -----------------------------");
            IToAdapt toAdapt = new ToAdapt();
            IAdapter adapter = new Adapter.Adapter(toAdapt);

            adapter.NormalMethod1();
            adapter.NormalMethod2();

            Console.WriteLine("----------------------------- Proxy -----------------------------");
            IServer server      = new Server();
            IServer proxyServer = new Proxy.Proxy(server);
            Client  proxyClient = new Client(proxyServer);

            proxyClient.Run();

            Console.WriteLine("----------------------------- Decorator -----------------------------");
            Decorator.Client decClient = new Decorator.Client();
            decClient.Run();

            Console.ReadKey(true);
        }
Example #3
0
        static void Main(string[] args)
        {
            //// ------------------------------- Abstract Factory Example -------------------------\\\\
            var abstractFactory = new AbstractFactoryClient();

            abstractFactory.StartApp();

            //// ------------------------------- Strategy Example -------------------------\\\\
            var strategyExample = new StrategyClient();

            strategyExample.StartApp();

            //// ------------------------------- Command Example -------------------------\\\\
            var commandExample = new Client();

            commandExample.StartCommandExample();


            //// ------------------------------- Singleton Example -------------------------\\\\
            var firstSingleton = MySingleton.GetInstance;

            firstSingleton.SayHello("Hello from First Singleton!");

            var secondSingleton = MySingleton.GetInstance;

            secondSingleton.SayHello("Hello from Second(??) Singleton");

            Console.ReadLine();
        }
Example #4
0
        private static void RunAbstractFactoryExample()
        {
            AbstractFactoryClient abstractFactoryClient = new AbstractFactoryClient();

            abstractFactoryClient.ExecuteCommand();

            Console.ReadKey();
        }
Example #5
0
        static void Main(string[] args)
        {
            var abstractFactoryDemo = new AbstractFactoryClient();

            abstractFactoryDemo.ExecuteDemo();

            Console.ReadKey();
        }
        /// <summary>
        /// You can also use the product family instead of using the Run method
        /// </summary>
        static void AbstractFactoryExample()
        {
            var client = new AbstractFactoryClient(new VictorianFactory());

            client.Run();

            client = new AbstractFactoryClient(new ModernFactory());
            client.Run();
        }
Example #7
0
        private static void UseÁbastractFatcory()
        {
            AbstractFactoryClient<VivienneBrand> currentClient = new AbstractFactoryClient<VivienneBrand>();
            currentClient.CreateProductLine();
            currentClient.DiplayAllItems();
            Console.WriteLine();

            AbstractFactoryClient<GucciBrand> newGucciClient = new AbstractFactoryClient<GucciBrand>();
            newGucciClient.CreateProductLine();
            newGucciClient.DiplayAllItems();
            Console.WriteLine();
        }
Example #8
0
        // Abctract Factory
        public static void TestAbstractFactory()
        {
            Console.WriteLine("- {0} -", typeof(AbstractFactory).Name);
            Console.WriteLine();

            AbstractFactoryClient client = new AbstractFactoryClient(new Factory1());

            client.InteractProducts();
            client = new AbstractFactoryClient(new Factory2());
            client.InteractProducts();

            Console.WriteLine("***************************************");
            Console.WriteLine();
        }
Example #9
0
        static void RunAbstractFactory()
        {
            // 工厂是抽象化的 即可以有多个工厂
            // 隐藏产品的实例化过程【隐藏生产过程】
            // 不同工厂生产不同类型产品【产品有共性(统一继承某产品基类),有产品组概念】
            // 单个工厂内的产品可以互相调用
            AbstractFactory       factory1 = new ConcreteFactory1();
            AbstractFactoryClient client1  = new AbstractFactoryClient(factory1);

            client1.Run();

            // Abstract factory #2
            AbstractFactory       factory2 = new ConcreteFactory2();
            AbstractFactoryClient client2  = new AbstractFactoryClient(factory2);

            client2.Run();
        }
Example #10
0
        static void Main(string[] args)
        {
            AbstractFactoryClient client = new AbstractFactoryClient(MANUFACTURES.PRODUCT1FACTORY);

            client.ProductList();
            client = new AbstractFactoryClient(MANUFACTURES.PRODUCT2FACTORY);
            client.ProductList();

            IBuilder builder1 = new ConcreteBuilder1();

            Console.WriteLine($"New Product created: {Manufacture.Construct(builder1)}");
            builder1 = new ConcreteBuilder2();
            Console.WriteLine($"New Product created: {Manufacture.Construct(builder1)}");

            Creator  creator = new Creator();
            IProduct product;

            product = creator.GetProduct(PRODUCT.TYPE1);
            Console.WriteLine(product.Description);
            product = creator.GetProduct(PRODUCT.TYPE2);
            Console.WriteLine(product.Description);

            LazyObject.Get("first");
            LazyObject.Get("second");
            LazyObject.ShowAll();
            LazyObject.Get("third");
            LazyObject.Get("first");
            LazyObject.ShowAll();

            Person personClient = new Client()
            {
                FirstName = "Ivan", SecondName = "Ivanov", OrdersCount = 5
            };
            Person personEmployee = new Employee()
            {
                FirstName = "Petr", SecondName = "Petrov", Salary = 1000
            };
            ToStringVisitor visitor = new ToStringVisitor();

            Console.WriteLine(visitor.DynamicVisit(personClient));
            Console.WriteLine(visitor.DynamicVisit(personEmployee));

            Console.WriteLine("Complete");
            Console.ReadKey();
        }
Example #11
0
        private void button4_Click(object sender, EventArgs e)
        {
            // 南昌工厂制作南昌的鸭脖和鸭架
            AbstractFactory nanChangFactory = new NanChangFactory();
            YaBo            nanChangYabo    = nanChangFactory.CreateYaBo();

            nanChangYabo.Print();
            YaJia nanChangYajia = nanChangFactory.CreateYaJia();

            nanChangYajia.Print();

            // 上海工厂制作上海的鸭脖和鸭架
            AbstractFactory shangHaiFactory = new ShangHaiFactory();

            shangHaiFactory.CreateYaBo().Print();
            shangHaiFactory.CreateYaJia().Print();

            // 自己写的
            AbstractFactoryClient.Test();
        }
Example #12
0
        static void Main(string[] args)
        {
            bool exitLoop = false;

            while (!exitLoop)
            {
                Console.WriteLine();
                Console.WriteLine("Please type the number of type of design patterns to veiw");
                Console.WriteLine("0 - Exit");
                Console.WriteLine("1 - Creational");
                Console.WriteLine("2 - Structural");
                Console.WriteLine("3 - Behaivoral");

                ConsoleKeyInfo keyInfo = Console.ReadKey();
                Console.WriteLine();

                switch (keyInfo.KeyChar.ToString())
                {
                case "0":
                    exitLoop = true;
                    break;

                case "1":
                    while (!exitLoop)
                    {
                        Console.WriteLine("Please select Creational Pattern to demo:");
                        Console.WriteLine("0 - Exit");
                        Console.WriteLine("1 - Simple Factory");
                        Console.WriteLine("2 - Factory Method");
                        Console.WriteLine("3 - Abstract Factory");
                        Console.WriteLine("4 - Builder");
                        Console.WriteLine("5 - Fluent Interface");
                        Console.WriteLine("6 - Prototype");
                        Console.WriteLine("7 - Singleton");

                        keyInfo = Console.ReadKey();
                        Console.WriteLine();

                        switch (keyInfo.KeyChar.ToString())
                        {
                        case "0":
                            exitLoop = true;
                            break;

                        case "1":
                            SimpleFactoryClient simpleFactoryClient = new SimpleFactoryClient();
                            simpleFactoryClient.PrintSimpleFactory();
                            break;

                        case "2":
                            FactoryMethodClient factoryMethodClient = new FactoryMethodClient();
                            factoryMethodClient.PrintFactoryMethod();
                            break;

                        case "3":
                            AbstractFactoryClient abstractFactoryClient = new AbstractFactoryClient();
                            abstractFactoryClient.PrintAbstractFactory();
                            break;

                        case "4":
                            BuilderClient builderClient = new BuilderClient();
                            builderClient.PrintBuilder();
                            break;

                        case "5":
                            FluentInterfaceClient fluentInterfaceClient = new FluentInterfaceClient();
                            fluentInterfaceClient.PrintFluentInterface();
                            break;

                        case "6":
                            PrototypeClient prototypeClient = new PrototypeClient();
                            prototypeClient.PrintPrototype();
                            break;

                        case "7":
                            SingletonClient singletonClient = new SingletonClient();
                            singletonClient.PrintSingleton();
                            break;

                        default:
                            Console.WriteLine("Selection must be 0-7");
                            break;
                        }
                    }

                    exitLoop = false;
                    break;

                case "2":
                    while (!exitLoop)
                    {
                        Console.WriteLine("Please select Structural Pattern to demo:");
                        Console.WriteLine("0 - Exit");
                        Console.WriteLine("1 - Adapter");
                        Console.WriteLine("2 - Facade");
                        Console.WriteLine("3 - Decorator");
                        Console.WriteLine("4 - Bridge");
                        Console.WriteLine("5 - Composite");
                        Console.WriteLine("6 - Proxy");
                        Console.WriteLine("7 - Flyweight");

                        keyInfo = Console.ReadKey();
                        Console.WriteLine();

                        switch (keyInfo.KeyChar.ToString())
                        {
                        case "0":
                            exitLoop = true;
                            break;

                        case "1":
                            AdapterClient adapterClient = new AdapterClient();
                            adapterClient.PrintAdapter();
                            break;

                        case "2":
                            FacadeClient facadeClient = new FacadeClient();
                            facadeClient.PrintFacade();
                            break;

                        case "3":
                            DecoratorClient decoratorClient = new DecoratorClient();
                            decoratorClient.PrintDecorator();
                            break;

                        case "4":
                            BridgeClient bridgeClient = new BridgeClient();
                            bridgeClient.PrintBridge();
                            break;

                        case "5":
                            CompositeClient compositeClient = new CompositeClient();
                            compositeClient.PrintComposite();
                            break;

                        case "6":
                            ProxyClient proxyClient = new ProxyClient();
                            proxyClient.PrintProxy();
                            break;

                        case "7":
                            FlyweightClient flyweightClient = new FlyweightClient();
                            flyweightClient.PrintFlyweight();
                            break;

                        default:
                            Console.WriteLine("Selection must be 0-7");
                            break;
                        }
                    }

                    exitLoop = false;
                    break;

                case "3":
                    while (!exitLoop)
                    {
                        Console.WriteLine("Please select Behaivoral Pattern to demo:");
                        Console.WriteLine("0 - Exit");
                        Console.WriteLine("1 - Iterator");
                        Console.WriteLine("2 - Observer");
                        Console.WriteLine("3 - Chain Of Responsibility");
                        Console.WriteLine("4 - State");
                        Console.WriteLine("5 - Template");
                        Console.WriteLine("6 - Command");
                        Console.WriteLine("7 - Visitor");
                        Console.WriteLine("8 - Strategy");
                        Console.WriteLine("9 - Interpreter");
                        Console.WriteLine("10 - Mediator");
                        Console.WriteLine("11 - Memento");

                        string entered = Console.ReadLine();
                        Console.WriteLine();

                        switch (entered)
                        {
                        case "0":
                            exitLoop = true;
                            break;

                        case "1":
                            IteratorClient iteratorClient = new IteratorClient();
                            iteratorClient.PrintIterator();
                            break;

                        case "2":
                            ObserverClient observerClient = new ObserverClient();
                            observerClient.PrintObserver();
                            break;

                        case "3":
                            ChainOfResponsibilityClient chainOfResponsibilityClient = new ChainOfResponsibilityClient();
                            chainOfResponsibilityClient.PrintChainOfResponsibility();
                            break;

                        case "4":
                            StateClient stateClient = new StateClient();
                            stateClient.PrintState();
                            break;

                        case "5":
                            TemplateClient templateClient = new TemplateClient();
                            templateClient.PrintTemplate();
                            break;

                        case "6":
                            CommandClient commandClient = new CommandClient();
                            commandClient.PrintCommand();
                            break;

                        case "7":
                            VisitorClient visitorClient = new VisitorClient();
                            visitorClient.PrintVisitor();
                            break;

                        case "8":
                            StrategyClient strategyClient = new StrategyClient();
                            strategyClient.PrintStrategy();
                            break;

                        case "9":
                            InterpreterClient interpreterClient = new InterpreterClient();
                            interpreterClient.PrintInterpreter();
                            break;

                        case "10":
                            MediatorClient mediatorClient = new MediatorClient();
                            mediatorClient.PrintMediator();
                            break;

                        case "11":
                            MementoClient mementoClient = new MementoClient();
                            mementoClient.PrintMemento();
                            break;

                        default:
                            Console.WriteLine("Selection must be 0-11");
                            break;
                        }
                    }

                    exitLoop = false;
                    break;

                default:
                    Console.WriteLine("Must enter number 0 -3");
                    break;
                }
            }

            Console.WriteLine("End of Design Patterns examples");
            Console.WriteLine("Type any key to exit");
            Console.ReadKey();
        }
Example #13
0
        static void Main(string[] args)
        {
            //FactoryMethod
            var shipFactory        = new ShipFactory();
            var fabricMethodClient = new FabricMethodClient(shipFactory);

            fabricMethodClient.Deliver();

            var cargoFactory = new CargoFactory();

            fabricMethodClient.SetTransportFactory(cargoFactory);
            fabricMethodClient.Deliver();

            //AbstractFactory
            var humanFactory          = new HumanUnitFactory();
            var abstractFactoryClient = new AbstractFactoryClient(humanFactory);

            abstractFactoryClient.DoSquad();

            var orkFactory = new OrkUnitFactory();

            abstractFactoryClient.SetUnitFactory(orkFactory);
            abstractFactoryClient.DoSquad();

            //Builder
            var opossumBuilder = new OpossumBuilder();
            var director       = new Director(opossumBuilder);
            var sectionalUnit  = director.GetUnit();

            sectionalUnit.DoStuff();

            var baldBuilder = new BaldBuilder();

            director.SetBuilder(baldBuilder);
            sectionalUnit = director.GetUnit();
            sectionalUnit.DoStuff();

            //Prototype
            var prototype = new PrototypeSample(2);

            prototype.SetProperty(1.0f);
            prototype.DoStuff();
            var clone = (PrototypeSample)prototype.Clone();

            clone.DoStuff();

            //Singleton
            Singleton.Instance.SingletonScream();

            //Adapter
            var adapterClient = new AdapterClient();

            adapterClient.DoStuff();

            //Bridge
            var bridgeClient = new BridgeClient();

            bridgeClient.DoStuff();

            //Composite
            var compositeClient = new CompositeClient();

            compositeClient.DoStuff();

            //Decorator
            var decoratorClient = new DecoratorClient();

            decoratorClient.DoStuff();

            //Facade
            var facadeClient = new Facade();

            facadeClient.DoStuff();

            //Flyweight
            var flyweightClient = new FlyweightClient();

            flyweightClient.DoStuff();

            //Proxy
            var proxyClient = new ProxyClient();

            proxyClient.DoStuff();

            //CoR
            var corClient = new CoRClient();

            corClient.DoStuff();

            //Command
            var commandClient = new CommandClient();

            commandClient.DoStuff();

            //Iterator
            var iteratorClient = new IteratorClient();

            iteratorClient.DoStuff();

            //Mediator
            var mediatorClient = new MediatorClient();

            mediatorClient.DoStuff();

            //Memento
            var mementoClient = new MementoClient();

            mementoClient.DoStuff();

            //Observer
            var observerClient = new ObserverClient();

            observerClient.DoStuff();

            //Strategy
            var strategyClient = new StrategyClient();

            strategyClient.DoStuff();

            //TemplateMethod
            var templateMethodClient = new TemplateMethodClient();

            templateMethodClient.DoStuff();

            //Visitor
            var visitorClient = new VisitorClient();

            visitorClient.DoStuff();
        }
Example #14
0
        static void Main(string[] args)
        {
            Patterns    pattern = Patterns.StructuralFacade;
            ExampleType type    = ExampleType.Structural;

            Console.WriteLine(new string('=', 42 + pattern.ToString().Length));
            Console.WriteLine(new string('=', 20) + " " + pattern + " " + new string('=', 20));
            Console.WriteLine(new string('=', 42 + pattern.ToString().Length));
            Console.WriteLine();
            switch (pattern)
            {
            case Patterns.CreationalAbstractFactory:

                // ==========================================================================================
                // Abstract Factory (Creational) - Creates an instance of several families of classes
                // ==========================================================================================

                #region Abstract Factory

                if (type == ExampleType.Structural)
                {
                    AbstractFactoryClient.RunStructural(new ConcreteFactory1());
                    AbstractFactoryClient.RunStructural(new ConcreteFactory2());
                }
                else
                {
                    // TODO: Abstract Factory Real-world example

                    /*
                     * Lion eats Wildebeest
                     * Wolf eats Bison
                     */
                }
                break;

                #endregion



            case Patterns.CreationalFactoryMethod:

                // ==========================================================================================
                // Factory Method (Creational) - Creates an instance of several derived classes
                // ==========================================================================================

                #region Factory Method

                if (type == ExampleType.Structural)
                {
                    FactoryMethodClient.RunStructural();
                }
                else
                {
                    // TODO: Factory Method Real-world example

                    /*
                     * Resume -------
                     *  SkillsPage
                     *  EducationPage
                     *  ExperiencePage
                     *
                     * Report -------
                     *  IntroductionPage
                     *  ResultsPage
                     *  ConclusionPage
                     *  SummaryPage
                     *  BibliographyPage
                     */
                }
                break;

                #endregion



            case Patterns.StructuralFacade:

                // ==========================================================================================
                // Facade (Structural) - A single class that represents an entire subsystem
                // ==========================================================================================

                #region Facade

                if (type == ExampleType.Structural)
                {
                    FacadeClient.RunStructural();
                }
                else
                {
                    // TODO: Facade Real-world example

                    /*
                     * Ann McKinsey applies for $125,000.00 loan
                     *
                     * Check bank for Ann McKinsey
                     * Check loans for Ann McKinsey
                     * Check credit for Ann McKinsey
                     *
                     * Ann McKinsey has been Approved
                     */
                }
                break;

                #endregion



            case Patterns.BehavioralObserver:

                // ==========================================================================================
                // Observer (Behavioral) - A way of notifying change to a number of classes
                // ==========================================================================================

                #region Observer

                if (type == ExampleType.Structural)
                {
                    // TODO: Observer Structural example

                    /*
                     * Observer X's new state is ABC
                     * Observer Y's new state is ABC
                     * Observer Z's new state is ABC
                     */
                }
                else
                {
                    // TODO: Observer Real-world example

                    /*
                     * Notified Sorros of IBM's change to $120.10
                     * Notified Berkshire of IBM's change to $120.10
                     *
                     * Notified Sorros of IBM's change to $121.00
                     * Notified Berkshire of IBM's change to $121.00
                     *
                     * Notified Sorros of IBM's change to $120.50
                     * Notified Berkshire of IBM's change to $120.50
                     *
                     * Notified Sorros of IBM's change to $120.75
                     * Notified Berkshire of IBM's change to $120.75
                     */
                }
                break;

                #endregion



            case Patterns.BehavioralIterator:
                break;

            case Patterns.BehavioralStrategy:
                break;

            case Patterns.StructuralProxy:
                break;

            case Patterns.StructuralComposite:
                break;

            case Patterns.CreationalSingleton:
                break;

            case Patterns.StructuralAdapter:
                break;

            case Patterns.BehavioralCommand:
                break;

            case Patterns.BehavioralState:
                break;

            case Patterns.BehavioralTemplateMethod:
                break;

            case Patterns.CreationalPrototype:
                break;

            case Patterns.StructuralBridge:
                break;

            case Patterns.StructuralDecorator:
                break;

            case Patterns.CreationalBuilder:
                break;

            case Patterns.BehavioralChainOfResponsibility:
                break;

            case Patterns.BehavioralMediator:
                break;

            case Patterns.StructuralFlyweight:
                break;

            case Patterns.BehavioralInterpreter:
                break;

            case Patterns.BehavioralMemento:
                break;

            case Patterns.BehavioralVisitor:
                break;
            }

            Console.ReadKey();
        }
Example #15
0
        static void Main(string[] args)
        {
            Console.WriteLine("-------Builder DEMO:-------");
            var coldDishesBuilder = new ColdDishesBuilder();

            Console.WriteLine("Let's build meat menu");
            var coldDishes = coldDishesBuilder.PrepareMeatMenu();

            coldDishes.showItems();
            Console.WriteLine("Total Cost: " + coldDishes.getCost());

            Console.WriteLine("Let's build veg menu");
            coldDishes = coldDishesBuilder.PrepareVegMenu();
            coldDishes.showItems();
            Console.WriteLine("Total Cost: " + coldDishes.getCost());
            Console.WriteLine();


            Console.WriteLine("-------Factory DEMO:-------");
            var         soupFactory = new SoupFactory();
            Ingredients ing1        = soupFactory.GetIngredients("ZEAMA");

            ing1.ShowIngredients();

            Ingredients ing2 = soupFactory.GetIngredients("CIORBA");

            ing2.ShowIngredients();

            Ingredients ing3 = soupFactory.GetIngredients("SALTWORT");

            ing3.ShowIngredients();

            Console.WriteLine();


            Console.WriteLine("-------Singleton DEMO:-------");
            SingleObject obj = SingleObject.GetInstance();

            obj.ShowAddress();

            Console.WriteLine();


            Console.WriteLine("-------Abstract factory DEMO:-------");
            var mondayFactory  = new ConcreteFactoryMondayMeal();
            var tuesdayFactory = new ConcreteFactoryTuesdayMeal();
            var client         = new AbstractFactoryClient(mondayFactory);

            Console.WriteLine("MONDAY Business lunch first meal: " + client.getFirstMeal());
            Console.WriteLine("MONDAY Business lunch second meal: " + client.getSecondMeal());

            client = new AbstractFactoryClient(tuesdayFactory);
            Console.WriteLine("TUESDAY Business lunch first meal: " + client.getFirstMeal());
            Console.WriteLine("TUESDAY Business lunch second meal: " + client.getSecondMeal());

            Console.WriteLine();


            Console.WriteLine("-------Prototype DEMO:-------");
            ConcretePromo originalObject = new ConcretePromo("Burger, cola", 50);

            Console.WriteLine("Original promo menu: " + originalObject.Menu + " and price: " + originalObject.Price);
            ConcretePromo clonedObject = (ConcretePromo)originalObject.Clone();

            Console.WriteLine("Cloned promo menu: " + clonedObject.Menu + " and price: " + clonedObject.Price);
        }