コード例 #1
0
ファイル: Main.cs プロジェクト: onurak/GOFDesignPatterns
        public static void Test()
        {
            var os = new ObjectStructure();
            os.Attach(new ConcreteElementA());
            os.Attach(new ConcreteElementB());

            os.Accept(new ConcreteVisitorA());
            os.Accept(new ConcreteVisitorB());
        }
コード例 #2
0
ファイル: Visitor.cs プロジェクト: jiabailie/self-projects
    public Client()
    {
        ObjectStructure o = new ObjectStructure();
        o.Attach(new ConcreteElementA());
        o.Attach(new ConcreteElementB());

        ConcreteVisitor1 v1 = new ConcreteVisitor1();
        ConcreteVisitor2 v2 = new ConcreteVisitor2();

        o.Accept(v1);
        o.Accept(v2);
    }
コード例 #3
0
ファイル: Program.cs プロジェクト: Jeffiy/DesignPatterns
        static void Main(string[] args)
        {
            ObjectStructure o = new ObjectStructure();

            o.Attach(new ConcreteElementA());
            o.Attach(new ConcreteElementB());

            ConcreteVisitor1 v1 = new ConcreteVisitor1();
            ConcreteVisitor2 v2 = new ConcreteVisitor2();

            o.Accept(v1);
            o.Accept(v2);
        }
コード例 #4
0
        public static void Demo(string[] args)
        {
            // Setup structure
            ObjectStructure o = new ObjectStructure();
            o.Attach(new ConcreteElementA());
            o.Attach(new ConcreteElementB());

            // Create visitor objects
            ConcreteVisitor1 v1 = new ConcreteVisitor1();
            ConcreteVisitor2 v2 = new ConcreteVisitor2();

            // Structure accepting visitors
            o.Accept(v1);
            o.Accept(v2);
        }
コード例 #5
0
ファイル: Main.cs プロジェクト: ManishLade/DesignPatterns-1
        public void Start()
        {
            var car   = new CarElement();
            var motor = new MotorCycleElement();

            ObjectStructure o = new ObjectStructure();

            o.Attach(car);
            o.Attach(motor);

            // Create visitor objects

            ServiceVisitor vService = new ServiceVisitor();
            RefuelVisitor  vRefuel  = new RefuelVisitor();

            // Structure accepting visitors

            o.Accept(vService);
            o.Accept(vRefuel);

            car.GoHome();
            motor.GoHome();
        }
コード例 #6
0
        public void VistorTest()
        {
            ObjectStructure o = new ObjectStructure();

            o.Attach(new Man());
            o.Attach(new Woman());

            Success v1 = new Success();

            o.Display(v1);

            Failing v2 = new Failing();

            o.Display(v2);

            Amativeness v3 = new Amativeness();

            o.Display(v3);

            Marriage v4 = new Marriage();

            o.Display(v4);
        }
コード例 #7
0
        static bool TestVisitorPattern()
        {
            Console.WriteLine("TESTING THE VISITOR DESIGN PATTERN: ");

            ObjectStructure o = new ObjectStructure();

            o.Attach(new Element1());
            o.Attach(new Element2());

            var v1 = new Visitor1();
            var v2 = new Visitor2();

            o.Accept(v1);
            //Output:
            //Element1 visited by Visitor1
            //Element2 visited by Visitor1

            o.Accept(v2);
            //Output:
            //Element1 visited by Visitor2 with override behaviour
            //Element2 visited by Visitor2 with override behaviour

            return(true);
        }
コード例 #8
0
        public void TestVisitorDiscount4TotalPrice()
        {
            decimal expected =
                this._shopcart[2].UnitPrice * this._shopcart[2].Amount * 0.9M +
                this._shopcart[3].UnitPrice * this._shopcart[3].Amount;
            decimal actual = 0;

            IObjectStructure checkout = new ObjectStructure();

            //Attach the elements into ObjectStructure
            this._shopcart.Where(item => item.ProductType.Equals(ProductTypeEnum.Living)).ToList().ForEach(item => {
                checkout.Attach(item);
            });

            //Accept all the elements and execute the strategy from certain Visitor
            checkout.Accept(new VisitorDiscount4TotalPrice());

            actual = checkout.Elements.Sum(x => x.TotalPrice);
            Assert.Equal(expected, actual);
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: MarsonShine/Books
        static void Main(string[] args)
        {
#if DECORATOR
            Decorator.Person ms = new Decorator.Person("MarsonShine");
            Console.WriteLine("\n 第一种妆扮:");
            TShirts    dtx = new TShirts();
            BigTrouser bt  = new BigTrouser();
            dtx.Decorate(ms);
            bt.Decorate(dtx);
            bt.Show();
#endif
#if Proxy
            SchoolGirl zhuqin = new SchoolGirl();
            zhuqin.Name = "祝琴";
            Proxy.Proxy ms = new Proxy.Proxy(zhuqin);
            ms.GiveChocolate();
            ms.GiveDolls();
            ms.GiveFlowers();
            Console.ReadLine();
#endif

#if ChanOfResposibility
            HandsetBrand hb;
            hb = new HandsetBrandN();
            hb.SetHandsetSoft(new HandsetGame());
            hb.Run();

            hb.SetHandsetSoft(new HandsetAddressList());
            hb.Run();

            HandsetBrand hb2;
            hb2 = new HandsetBrandM();
            hb2.SetHandsetSoft(new HandsetGame());
            hb2.Run();

            hb2.SetHandsetSoft(new HandsetAddressList());
            hb2.Run();
#endif
#if ChainOfResiposibility
            CommonManager  jinli       = new CommonManager("jinli");
            Majordomo      zongjian    = new Majordomo("zongjian");
            GeneralManager zhongjingli = new GeneralManager("zhongjinli");
            jinli.SetSuperior(jinli);
            zongjian.SetSuperior(zhongjingli);

            Request request = new Request();
            request.RequestType    = "请假";
            request.RequestContent = "我要请假";
            request.Number         = 1;
            jinli.RequestApplications(request);

            Request request2 = new Request();
            request2.RequestType    = "请假";
            request2.RequestContent = "我要请假";
            request.Number          = 4;
            jinli.RequestApplications(request2);

            Request request3 = new Request();
            request3.RequestType    = "请假";
            request3.RequestContent = "我还是要请假";
            request.Number          = 500;
            jinli.RequestApplications(request3);
#endif
            ObjectStructure o = new ObjectStructure();
            o.Attach(new Man());
            o.Attach(new Woman());

            Success v1 = new Success();
            o.Display(v1);

            Failing v2 = new Failing();
            o.Display(v2);

            // 根据业务需求得知文件格式
            var fileType      = Enum.Parse <FileType>("Word");
            var wordConvertor = PdfConvertorFactory.Create(fileType);
            wordConvertor.Convert("example.docx");
            fileType = Enum.Parse <FileType>("Wps");
            var wpsConvertor = PdfConvertorFactory.Create(fileType);
            wpsConvertor.Convert("example.wps");

            // 策略模式
            var vertor   = new Strategy.WordToPdfConvertor();
            var strategy = new StrategyContext(vertor);
            strategy.DoWork("example.docx");
            var excel = new Strategy.ExcelToPdfConvertor();
            strategy = new StrategyContext(excel);
            strategy.DoWork("example.xlsx");
            // 策略模式+工厂模式 封装部分相同逻辑,又有部分业务不同的逻辑变化

            // 抽象工厂模式
            IConvertorFactory factory = new WordToPdfConvertorFactory();
            Console.WriteLine("==========抽象工厂============");
            factory.Create().Convert("example.docx");
            // 原型模式
            Console.WriteLine("==========原型模式============");
            Resume r = new Resume("marson shine");
            r.SetPersonalInfo("男", "27");
            r.SetWorkExperience("6", "kingdee.cpl");
            r.Display();
            // 如果我要复制三个 Resume,则不需要实例化三次,而是调用Clone()即可
            var r2 = (Resume)r.Clone();
            var r3 = (Resume)r.Clone();
            r2.SetWorkExperience("5", "yhglobal.cpl");
            r2.Display();
            r3.SetWorkExperience("3", "che100.cpl");
            r3.Display();

            // 观察者模式
            Console.WriteLine("==========观察者模式============");
            StudentOnDuty studentOnDuty = new StudentOnDuty();
            var           student       = new StudentObserver("marson shine", studentOnDuty);
            studentOnDuty.Attach(student);
            studentOnDuty.Attach(new StudentObserver("summer zhu", studentOnDuty));
            studentOnDuty.Notify();
            studentOnDuty.UpdateEvent += student.Update;
            Console.WriteLine("==========观察者模式============");

            Console.WriteLine("==========状态模式============");
            var client = new Client(new PerfectState());
            client.Handle();
            client.Handle();
            client.Handle();
            Console.WriteLine("==========状态模式============");

            Console.WriteLine("==========备忘录模式============");
            var originator = new Originator();
            originator.State = "On";
            originator.Show();

            MementoManager manager = new MementoManager();
            manager.Record(originator.CreateMemento());

            originator.State = "Off";
            originator.Show();

            originator.SetMemento(manager.Memento);
            originator.Show();

            Console.WriteLine("==========备忘录模式============");

            Console.WriteLine("==========规格模式============");
            // 只要华为品牌的手机
            ISpecification <Mobile> huaweiExpression = new ExpressionSpecification <Mobile>(p => p.Type == "华为");
            // 三星手机
            ISpecification <Mobile> samsungExpression = new ExpressionSpecification <Mobile>(p => p.Type == "三星");
            // 华为和三星
            ISpecification <Mobile> huaweiAndsamsungExpression = huaweiExpression.And(samsungExpression);

            List <Mobile> mobiles = new List <Mobile> {
                new Mobile("华为", 4888),
                new Mobile("三星", 6888),
                new Mobile("苹果", 7888),
                new Mobile("小米", 3888)
            };
            var samsungs          = mobiles.FindAll(p => samsungExpression.IsSatisfiedBy(p));
            var huaweis           = mobiles.FindAll(p => huaweiExpression.IsSatisfiedBy(p));
            var samsungAndhuaweis = mobiles.FindAll(p => huaweiAndsamsungExpression.IsSatisfiedBy(p));
            Console.WriteLine("==========规格模式============");

            Console.WriteLine("==========时间格式化-本地文化============");
            Console.WriteLine(DateTime.Now.ToString());
            Console.WriteLine("ShortDatePattern:" + CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern);
            Console.WriteLine("LongDatePattern:" + CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern);
            Console.WriteLine("LongTimePattern:" + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern);
            CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
            culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
            culture.DateTimeFormat.LongTimePattern  = "h:mm:ss.fff";
            CultureInfo.CurrentCulture = culture;
            Console.WriteLine(DateTime.Now.ToString());
            Console.WriteLine("开始后台线程时间格式化");
            Task.Run(() => {
                Console.WriteLine("后台线程:" + DateTime.Now.ToString());
            });
            Console.WriteLine("==========时间格式化-本地文化============");
        }
コード例 #10
0
        static void Main(string[] args)
        {
            #region Strategy

            //First Step
            Console.WriteLine("Initialize Strategy");

            long[] inputArray = new long[20];
            Random radom      = new Random();

            for (int strategy = 0; strategy < inputArray.Length; strategy++)
            {
                inputArray[strategy] = radom.Next(100);
            }

            foreach (long number in inputArray)
            {
                Console.WriteLine(number);
            }
            Console.ReadKey();

            //Second Step
            //Strategy 1
            var alg = new BubbleSort();
            alg.Sort(inputArray);
            Console.WriteLine("sort numbers");

            foreach (long number in inputArray)
            {
                Console.WriteLine(number);
            }

            Console.ReadKey();

            //Strategy 2
            var alg2 = new SelectionSort();
            alg2.Sort(inputArray);
            Console.WriteLine("sort numbers");
            foreach (long number in inputArray)
            {
                Console.WriteLine(number);
            }

            Console.ReadKey();

            //Apply Strategy Patterns
            Strategy.Context ctx = new Strategy.Context(new SelectionSort());
            ctx.ContextInterface(inputArray);
            Console.WriteLine("sort numbers");

            foreach (long number in inputArray)
            {
                Console.WriteLine(number);
            }

            Console.ReadKey();
            Console.WriteLine("Finalize Strategy" + Environment.NewLine);

            #endregion

            #region ChainOfResponsability

            Console.WriteLine("ChainOfResponsability Initialize");

            // First Step
            Validate validate = new Validate();
            Console.WriteLine(validate.ValidateUser("Test", "Test").ToString());

            ///Apply ChainOfResponsability pattern
            ChainOfResponsability.Form   valform   = new ChainOfResponsability.Form();
            ChainOfResponsability.Server valserver = new ChainOfResponsability.Server();
            BD valBD = new BD();

            valform.setSucessor(valserver);
            valserver.setSucessor(valBD);

            Console.WriteLine(valform.ValidateUser("Teste", "Teste").ToString());

            Console.WriteLine("ChainOfResponsability Finalize" + Environment.NewLine);

            #endregion

            #region Command

            Console.WriteLine("Command Initialize");

            //Configure Receiver
            Command.Server server = new Command.Server();

            //Create command and configure receiver.
            CommandAbstract cmd = new ServerCommand(server);

            //Configure invoker
            Command.Formulario form = new Command.Formulario();

            form.SetCommand(cmd);
            form.ClickValidate();
            Console.WriteLine("Command Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region Iterator

            Console.WriteLine("Iterator Initialize");

            //Create concrete aggregate
            Team team = new Team();
            team[0] = "Luiz";
            team[0] = "Alex";
            team[0] = "Rodrigo";
            team[0] = "Renan";

            ConcreteIterator i = new ConcreteIterator(team);

            Console.WriteLine("Show team's members");

            Object item = i.First();

            while (item != null)
            {
                Console.WriteLine(item);
                item = i.Next();
            }

            Console.WriteLine("Iterator Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region Mediator

            Console.WriteLine("Mediator Initialize");

            ConcreteMediator concreteMediator = new ConcreteMediator();
            Support          support          = new Support(concreteMediator);
            User             user             = new User(concreteMediator);

            concreteMediator.Suporte = support;
            concreteMediator.Usuario = user;

            support.Send("Hello user");
            user.Send("Hello support");

            Console.WriteLine("Mediator Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region Memento

            Console.WriteLine("Memento Initialize");

            //Create originator
            Originator people = new Originator();
            people.State = "Bored";

            //Create caretaker
            Caretaker caretaker = new Caretaker();
            caretaker.Memento = people.CreateMemento();

            people.State = "Happy";
            Console.WriteLine("Actual State:" + people.State);

            people.setMemento(caretaker.Memento);
            Console.WriteLine("Restore State: " + people.State);

            Console.WriteLine("Memento Finalize" + Environment.NewLine);

            #endregion

            #region Observer

            Console.WriteLine("Observer Initialize");

            Balance balanco = new Balance();
            Sale    venda   = new Sale(balanco);

            balanco.Attach(venda);

            balanco.Iniciar();
            balanco.Notify();

            balanco.Finalizar();
            balanco.Notify();

            venda.Iniciar();

            //After remove observer
            balanco.Detach(venda);

            balanco.Iniciar();
            balanco.Notify();

            venda.Iniciar();

            Console.WriteLine("Observer Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region State

            Console.WriteLine("State Initialize");

            Connection connection = new Connection(new ConnectionOpened());

            connection.Open();
            connection.Close();

            Console.WriteLine("State Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region Template Method

            Console.WriteLine("Template Method Initialize");

            Correction proofCorrecion = new ProofCorrection();
            proofCorrecion.Process();

            Correction writingCorrection = new WritingCorrection();
            writingCorrection.Process();

            Console.WriteLine("Template Method Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region Visitor

            Console.WriteLine("Visitor Initialize");

            //Config structure
            ObjectStructure objectStructure = new ObjectStructure();

            objectStructure.Attach(new ConcreteElementA());
            objectStructure.Attach(new ConcreteElementB());

            //Create Visitors
            ConcreteVisitor1 concreteVisitor1 = new ConcreteVisitor1();
            ConcreteVisitor2 concreteVisitor2 = new ConcreteVisitor2();

            objectStructure.Accept(concreteVisitor1);
            objectStructure.Accept(concreteVisitor2);

            Console.WriteLine("Visitor Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region Interpreter

            Console.WriteLine("Interpreter Initialize");

            string roman = "MCMXXVIII";
            Interpreter.Context context = new Interpreter.Context(roman);

            List <Expression> tree = new List <Expression>();
            tree.Add(new ThousandExpression());
            tree.Add(new HundredExpression());
            tree.Add(new TenExpression());
            tree.Add(new OneExpression());

            foreach (Expression exp in tree)
            {
                exp.Interpret(context);
            }

            Console.WriteLine("{0} = {1}", roman, context.Output);

            Console.WriteLine("Interpreter Finalize" + Environment.NewLine);
            Console.ReadKey();

            #endregion
        }