Example #1
0
 public void ProxyTest()
 {
     int x = 1;
     int y = 1;
     MathProxy mp = new MathProxy();
     double result = mp.Add(x, y) + mp.Sub(x, y);
 }
Example #2
0
        public List <ScoreStatus> GetWinner() //kan vara fler än en vinnare
        {
            List <Scores>      ScoresList       = new List <Scores>();
            List <Game>        GamesList        = new List <Game>();
            List <ScoreStatus> ScoresStatusList = new List <ScoreStatus>();

            ScoreCollection.Reading(); //läser in användarna
            GameCollection.Reading();  //läser in alla matcher
            PersonCollection.Reading();

            var getScores     = ScoreCollection.GetEnumerator();
            var getGames      = GameCollection.GetEnumerator();
            var getAllPersons = PersonCollection.GetEnumerator();

            foreach (var items in getScores)
            {
                ScoresList.Add(items);
            }

            foreach (var items in getGames)
            {
                GamesList.Add(items);
            }

            var percentage   = 0.0;
            var amountScores = 0; //Hur många gånger en person återkommer i Gamesfilen
            var amountGames  = 0;

            foreach (var items in getAllPersons)
            {
                var text = $"{items.ContestNumber} {items.FirstName} {items.LastName}";

                amountScores = ScoresList.Where(x => x.Winner == text).Count();

                amountGames = GamesList.Where(x => x.PersonOne == text || x.PersonTwo == text).Count();

                // Create math proxy
                MathProxy proxy = new MathProxy();

                if (amountGames >= 10)
                {
                    if (amountScores == 0)
                    {
                        percentage = proxy.Mul(amountScores, amountGames);
                    }

                    percentage = proxy.Div((amountScores * 100), amountGames);

                    var ScoresStatus = new ScoreStatus(amountGames, amountScores, items.FirstName, items.LastName, percentage, items.ContestNumber);
                    ScoresStatusList.Add(ScoresStatus);
                }
            }

            Builder.Append($"\n{DateTime.Now} - Användaren får den slutgiltiga vinnaren utskriven ");
            File.AppendAllText(FilePath, Builder.ToString());
            Builder.Clear();

            return(ScoresStatusList);
        }
Example #3
0
        private static void ProxyDemo()
        {
            var proxy = new MathProxy();

            Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));
        }
 public void SetUp()
 {
     _math = new Mock <ProxyPattern.Subjects.IMath>();
     _math.Setup(x => x.Add(It.IsAny <double>(), It.IsAny <double>())).Returns((double x, double y) => { return(x + y); });
     _math.Setup(x => x.Sub(It.IsAny <double>(), It.IsAny <double>())).Returns((double x, double y) => { return(x - y); });
     _math.Setup(x => x.Mul(It.IsAny <double>(), It.IsAny <double>())).Returns((double x, double y) => { return(x * y); });
     _math.Setup(x => x.Div(It.IsAny <double>(), It.IsAny <double>())).Returns((double x, double y) => { return(x / y); });
     _proxy = new MathProxy(_math.Object);
 }
Example #5
0
        public void Execute()
        {
            MathProxy proxy = new MathProxy();

            Console.WriteLine("4 + 2 = {0}", proxy.Add(4, 2));
            Console.WriteLine("4 - 2 = {0}", proxy.Sub(4, 2));
            Console.WriteLine("4 / 2 = {0}", proxy.Div(4, 2));
            Console.WriteLine("4 * 2 = {0}", proxy.Mul(4, 2));
        }
Example #6
0
        public static void TestMathProxy()
        {
            var proxyImplement = new MathProxy();

            Assert.AreEqual(6, proxyImplement.Add(4, 2));
            Assert.AreEqual(2, proxyImplement.Sub(4, 2));
            Assert.AreEqual(8, proxyImplement.Mul(4, 2));
            Assert.AreEqual(2, proxyImplement.Div(4, 2));
        }
        public void Main()
        {
            var proxy = new MathProxy();

            Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));
        }
        static void Main()
        {
            MathProxy proxy = new MathProxy();

            //Mathクラスの利用を意識せずに処理を実行できる
            Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));
        }
        public static void ProxyRealWorld()
        {
            MathProxy proxy = new MathProxy();

            // Do the math
            Log.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            Log.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
            Log.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
            Log.WriteLine("4 / 2 = " + proxy.Div(4, 2));
        }
Example #10
0
        public ActionResult Index()
        {
            MathProxy proxy = new MathProxy();
            double    a     = 5.5;
            double    b     = 10.5;

            ViewBag.Value1       = a;
            ViewBag.Value2       = b;
            ViewBag.ProxyMessage = proxy.Add(a, b);
            return(View());
        }
        private static void ProxyPattern()
        {
            // create math proxy
            MathProxy proxy = new MathProxy();

            // do the math
            Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));
        }
Example #12
0
            public void Main()
            {
                // Create math proxy
                IMath proxy = new MathProxy();

                // Do the math
                Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
                Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
                Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
                Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));
            }
Example #13
0
        static void RunProxyRealWorld()
        {
            // Create math proxy
            MathProxy proxy = new MathProxy();

            // Do the math
            Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));
        }
Example #14
0
        private static void Proxy()
        {
            //create proxy
            MathProxy proxy = new MathProxy();

            //Do your calculations
            Console.WriteLine("\n ----------------- Using Math Proxy to do my Calculations ----------------------");
            Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            Console.WriteLine("4 - 2 = " + proxy.Subtract(4, 2));
            Console.WriteLine("4 * 2 = " + proxy.Multiply(4, 2));
            Console.WriteLine("4 / 2 = " + proxy.Divide(4, 2));
        }
Example #15
0
        static void Main(string[] args)
        {
            #region 01 Creation Patterns
            #region 01 Abstract Factory
            //ISmartPhone smartPhone;
            //INormalPhone normalPhone;

            IMobilePhone nokiaPhone = new Nokia();

            Console.WriteLine(nokiaPhone.GetNormalPhone().GetModelDetials());
            Console.WriteLine(nokiaPhone.GetSmartPhone().GetModelDetials());


            IMobilePhone samsungPhone = new Samsung();
            Console.WriteLine(samsungPhone.GetNormalPhone().GetModelDetials());
            Console.WriteLine(samsungPhone.GetSmartPhone().GetModelDetials());
            #endregion


            #region 02 Factory Method
            //Document[] documents = new Document[2];
            var documents = new List <Document>();
            documents.Add(new Resume());
            documents.Add(new Report());

            foreach (var item in documents)
            {
                Console.WriteLine("-" + item.GetType().Name);
                foreach (var page in item.Pages)
                {
                    Console.WriteLine("   -" + page.GetType().Name);
                }
            }
            #endregion

            #endregion

            #region 02 Structural Patterns
            #region 07 Proxy
            IMath proxy = new MathProxy();

            Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));
            #endregion
            #endregion

            #region 03 Behavioral Patterns
            #endregion
            FinishProgram();
        }
Example #16
0
  public static void Main( string[] args )
  {
    // Create math proxy
    MathProxy p = new MathProxy();

    // Do the math
    Console.WriteLine( "4 + 2 = {0}", p.Add( 4, 2 ) );
    Console.WriteLine( "4 - 2 = {0}", p.Sub( 4, 2 ) );
    Console.WriteLine( "4 * 2 = {0}", p.Mul( 4, 2 ) );
    Console.WriteLine( "4 / 2 = {0}", p.Div( 4, 2 ) );

    Console.Read();
  }
Example #17
0
        static void Main(string[] args)
        {
            // Create math proxy
            MathProxy proxy = new MathProxy();

            // Do the math
            Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));

            // Wait for user
            Console.ReadKey(true);
        }
Example #18
0
    static void Main()
    {
      // Create math proxy
      IMath p = new MathProxy();

      // Do the math
      Console.WriteLine("4 + 2 = " + p.Add(4, 2));
      Console.WriteLine("4 - 2 = " + p.Sub(4, 2));
      Console.WriteLine("4 * 2 = " + p.Mul(4, 2));
      Console.WriteLine("4 / 2 = " + p.Div(4, 2));

      // Wait for user
      Console.Read();
    }
Example #19
0
    static void Main()
    {
        // Create math proxy
        IMath p = new MathProxy();

        // Do the math
        Console.WriteLine("4 + 2 = " + p.Add(4, 2));
        Console.WriteLine("4 - 2 = " + p.Sub(4, 2));
        Console.WriteLine("4 * 2 = " + p.Mul(4, 2));
        Console.WriteLine("4 / 2 = " + p.Div(4, 2));

        // Wait for user
        Console.Read();
    }
Example #20
0
        //Замісник - Proxy
        public Run Proxy()
        {
            Console.WriteLine("\nProxy:");

            // Create math proxy
            MathProxy p = new MathProxy();

            // Do the math
            Console.WriteLine("4 + 2 = " + p.Add(4, 2));
            Console.WriteLine("4 - 2 = " + p.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + p.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + p.Div(4, 2));

            return(this);
        }
Example #21
0
        public void CheckCupWinner(string cupName)
        {
            List <ScoreStatus> ScoresStatusList = new List <ScoreStatus>();

            GamePersonTesting getGameAndUser = new GamePersonTesting();

            var getAllPersons = getGameAndUser.PersonData();

            var    returned     = "";
            int    amountScores = 0;
            int    amountGames  = 0;
            double percentage   = 0;

            var ScoresList = getGameAndUser.ScoresData();
            var GamesList  = getGameAndUser.GamesData();

            var getOutGames = GamesList.Where(x => x.Name == cupName);

            foreach (var items in getAllPersons)
            {
                var text = $"{items.ContestNumber} {items.FirstName} {items.LastName}";

                amountScores = ScoresList.Where(x => x.Winner == text).Count();

                amountGames = getOutGames.Where(x => x.PersonOne == text || x.PersonTwo == text).Count();
                MathProxy proxy = new MathProxy();

                if (amountGames >= 10)
                {
                    if (amountScores == 0)
                    {
                        percentage = proxy.Mul(amountScores, amountGames);
                    }

                    percentage = proxy.Div((amountScores * 100), amountGames);

                    var ScoresStatus = new ScoreStatus(amountGames, amountScores, items.FirstName, items.LastName, percentage, items.ContestNumber);
                    ScoresStatusList.Add(ScoresStatus);
                }
            }

            var sort = ScoresStatusList.OrderByDescending(x => x.Percentage).FirstOrDefault();

            returned = $"{sort.ContestNumber} {sort.FirstName} {sort.LastName}";

            Assert.True(sort.ContestNumber == 1 && sort.FirstName == "Emma" && sort.LastName == "Pestin");
        }
Example #22
0
        private static void ShowProxy()
        {
            Console.WriteLine("================================================");
            Console.WriteLine("Pattern code (Proxy):");
            Proxy proxy = new Proxy();

            proxy.Request();
            Console.WriteLine("\nReal code (Proxy):");
            // Create math proxy
            MathProxy mathProxy = new MathProxy();

            // Do the math
            Console.WriteLine("4 + 2 = " + mathProxy.Add(4, 2));
            Console.WriteLine("4 - 2 = " + mathProxy.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + mathProxy.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + mathProxy.Div(4, 2));
        }
Example #23
0
        static void Main(string[] args)
        {
            // Create math proxy

            MathProxy proxy = new MathProxy();

            // Do the math

            Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));

            // Wait for user

            Console.ReadKey();
        }
Example #24
0
        public void ProxyTest()
        {
            // Create math proxy

            MathProxy proxy = new MathProxy();

            // Do the math

            Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));

            // Wait for user

            Console.ReadKey();
        }
Example #25
0
        static void ProxyTester()
        {
            #region sample 1
            var proxy = new Proxy();
            proxy.Request();
            #endregion

            #region sample 2
            var proxyImplement = new MathProxy();

            // Do the math
            Console.WriteLine("4 + 2 = " + proxyImplement.Add(4, 2));
            Console.WriteLine("4 - 2 = " + proxyImplement.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + proxyImplement.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + proxyImplement.Div(4, 2));
            #endregion
        }
Example #26
0
        private static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            IMathProxy mathProxy = new MathProxy();

            var result = await mathProxy.Add(2, 2);

            Console.WriteLine($"Add : {result}");

            result = await mathProxy.Sub(4, 2);

            Console.WriteLine($"Sub : {result}");

            result = await mathProxy.Mul(2, 2);

            Console.WriteLine($"Mul : {result}");

            var resultDiv = await mathProxy.Div(10, 2);

            Console.WriteLine($"Div : {resultDiv}");
        }
Example #27
0
        public string Calculator(int roundOne, int roundTwo, int pointOne, int pointTwo, string firstPerson, string secondPerson)
        {
            var winner = "";

            MathProxy proxy = new MathProxy();

            var one = proxy.Sub(pointOne, pointTwo);
            var two = proxy.Sub(pointTwo, pointOne);

            if (roundOne == 0 && roundTwo == 0) //Om totalpoäng för spelet
            {
                if (one > two)
                {
                    winner = firstPerson;
                }

                else if (two > one)
                {
                    winner = secondPerson;
                }
            }

            else
            {
                if (roundOne > roundTwo)
                {
                    winner = firstPerson;
                }
                else if (roundTwo > roundOne)
                {
                    winner = secondPerson;
                }
            }

            return(winner);
        }
Example #28
0
        public string GetWinnerOfSpecificContest(string name)
        {
            List <Scores>      ScoresList       = new List <Scores>();
            List <Game>        GamesList        = new List <Game>();
            List <ScoreStatus> ScoresStatusList = new List <ScoreStatus>();

            ScoreCollection.Reading(); //läser in användarna
            GameCollection.Reading();  //läser in alla matcher
            PersonCollection.Reading();

            var getScores     = ScoreCollection.GetEnumerator();
            var getGames      = GameCollection.GetEnumerator();
            var getAllPersons = PersonCollection.GetEnumerator();

            foreach (var items in getScores)
            {
                ScoresList.Add(items);
            }

            foreach (var items in getGames)
            {
                if (items.Name == name)
                {
                    GamesList.Add(items);
                }
            }

            var percentage   = 0.0;
            var amountScores = 0; //Hur många gånger en person återkommer i Gamesfilen
            var amountGames  = 0;

            foreach (var items in getAllPersons)
            {
                var text = $"{items.ContestNumber} {items.FirstName} {items.LastName}";

                amountScores = ScoresList.Where(x => x.Winner == text).Count();

                amountGames = GamesList.Where(x => x.PersonOne == text || x.PersonTwo == text).Count();

                // Create math proxy
                MathProxy proxy = new MathProxy();

                if (amountGames >= 10)
                {
                    if (amountScores == 0)
                    {
                        percentage = proxy.Mul(amountScores, amountGames);
                    }

                    percentage = proxy.Div((amountScores * 100), amountGames);

                    var ScoresStatus = new ScoreStatus(amountGames, amountScores, items.FirstName, items.LastName, percentage, items.ContestNumber);
                    ScoresStatusList.Add(ScoresStatus);
                }
            }


            if (ScoresStatusList.Count > 0)
            {
                var sort = ScoresStatusList.OrderByDescending(x => x.Percentage).FirstOrDefault();

                //return $"Årets champion: {sort.FirstName} {sort.LastName} vinnar andel: {sort.Percentage}%";
                return($"{sort.ContestNumber} {sort.FirstName} {sort.LastName}");
            }
            else
            {
                return("Ingen användare har spelat mer än 10 matcher");
            }
        }
Example #29
0
 public void Initialize()
 {
     proxy = new MathProxy();
 }
Example #30
0
        private static void Main()
        {
            const DesignPatterns designPatterns = DesignPatterns.装饰模式;

            switch (designPatterns)
            {
            case DesignPatterns.单例模式:
                Singleton singleton = Singleton.GetInstance();
                Console.WriteLine(singleton.Say());
                break;

            case DesignPatterns.工厂模式:
                //简单工厂
                BookFactory bookFactory  = new BookFactory();
                IBook       chineseBook1 = bookFactory.CreateBook("语文");
                IBook       mathBook1    = bookFactory.CreateBook("数学");
                chineseBook1.Info();
                mathBook1.Info();
                //工厂方法
                ChineseBookFactory chineseBookFactory = new ChineseBookFactory();
                MathBookFactory    mathBookFactory    = new MathBookFactory();
                IBook chineseBook2 = chineseBookFactory.CreateBook();
                IBook mathBook2    = mathBookFactory.CreateBook();
                chineseBook2.Info();
                mathBook2.Info();
                //抽象工厂
                FirstGradeBookFactory firstGradeBookFactory = new FirstGradeBookFactory();
                SecondGradeFactory    secondGradeFactory    = new SecondGradeFactory();
                IBook chineseBook3 = firstGradeBookFactory.CreateChineseBook();
                IBook mathBook3    = firstGradeBookFactory.CreateMathBook();
                chineseBook3.Info();
                mathBook3.Info();
                IBook chineseBook4 = secondGradeFactory.CreateChineseBook();
                IBook mathBook4    = secondGradeFactory.CreateMathBook();
                chineseBook4.Info();
                mathBook4.Info();
                break;

            case DesignPatterns.装饰模式:
                Zhangsan     zhangsan     = new Zhangsan();
                ZhangsanSayA zhangsanSayA = new ZhangsanSayA();
                ZhangsanSayB zhangsanSayB = new ZhangsanSayB();
                zhangsanSayA.Tell(zhangsan);
                zhangsanSayB.Tell(zhangsanSayA);
                zhangsanSayB.Say();
                break;

            case DesignPatterns.外观模式:
                Lisi lisi = new Lisi();
                lisi.OneDay();
                break;

            case DesignPatterns.代理模式:
                MathProxy proxy = new MathProxy();
                Console.WriteLine("8 + 2 = " + proxy.Add(8, 2));
                Console.WriteLine("8 - 2 = " + proxy.Sub(8, 2));
                Console.WriteLine("8 * 2 = " + proxy.Mul(8, 2));
                Console.WriteLine("8 / 2 = " + proxy.Div(8, 2));
                break;

            case DesignPatterns.观察者模式:
                //被观察者
                Hero hero = new Hero();
                //添加观察者
                hero.AttachObserver(new Monster());
                hero.AttachObserver(new Trap());
                hero.AttachObserver(new Treasure());
                //通知观察者
                hero.Move();
                break;
            }
        }
Example #31
0
        static void Main(string[] args)
        {
            /////////////////////// Strategy Pattern
            //IHornStrategy audiHorn = new AudiHornStrategy();
            //IHornStrategy bmwHorn = new BMWHornStrategy();

            //Car car = new Car(audiHorn);
            //Car carb = new Car(bmwHorn);

            //Console.WriteLine(car.PressHorn());
            //Console.WriteLine(carb.PressHorn());
            //////////////////////////

            ////////////////////////// Observer Pattern
            //Console.WriteLine("Please enter the temperature?");
            //string temperature = Console.ReadLine();
            //IObservable wheaterStation = new WheaterStation();

            //IObserver mobilePhone = new MobilePhone();
            //wheaterStation.Add(mobilePhone);

            //IObserver tablet = new Tablet();
            //wheaterStation.Add(tablet);

            //wheaterStation.Notify(temperature);
            //////////////////////////

            ////////////////////////// Decorator Pattern

            //Beverage cofee = new Expresso(new CaramelDecorator());
            //Beverage tea = new Tea(new MilkDecorator());

            //Console.WriteLine("Cofee with caramel: " + cofee.Cost());
            //Console.WriteLine("Tea with milk: " + tea.Cost());
            //////////////////////////

            ////////////////////////// FactoryMethodPattern
            //ShapeFactory shapeFactory = new ShapeFactory();

            //var shape = shapeFactory.GetShape(ShapeTypes.Circle);
            //Console.WriteLine("You drew a " + shape.Draw());

            //var shape1 = shapeFactory.GetShape(ShapeTypes.Rectangle);
            //Console.WriteLine("You drew a " + shape1.Draw());

            //var shape2 = shapeFactory.GetShape(ShapeTypes.Square);
            //Console.WriteLine("You drew a " + shape2.Draw());
            //////////////////////////

            ////////////////////////// AbstractFactoryPattern
            //IMobilePhone nokiaMobilePhone = new Nokia();
            //MobileAbstractFactory nokiaClient = new MobileAbstractFactory(nokiaMobilePhone);

            //Console.WriteLine("********* NOKIA **********");
            //Console.WriteLine(nokiaClient.GetSmartPhoneModelDetails());
            //Console.WriteLine(nokiaClient.GetNormalPhoneModelDetails());

            //IMobilePhone samsungMobilePhone = new Samsung();
            //MobileAbstractFactory samsungClient = new MobileAbstractFactory(samsungMobilePhone);

            //Console.WriteLine("******* SAMSUNG **********");
            //Console.WriteLine(samsungClient.GetSmartPhoneModelDetails());
            //Console.WriteLine(samsungClient.GetNormalPhoneModelDetails());
            //////////////////////////

            ////////////////////////// Adapter Pattern
            //IAdapter adapter = null;

            //Let emulate the decision where the choice of using the underlying system is made
            //Console.WriteLine("Enter which library you wanna use to do operation {1,2}");
            //int x = Console.Read();

            //if (x == '1')
            //{
            //    //Let us choose to use Library one to do something
            //    adapter = new AdapterOne();
            //}
            //else if (x == '2')
            //{
            //    //Let us choose to use Library two to do something
            //    adapter = new AdapterTwo();
            //}

            ////Just do the operation now
            //adapter.Do();
            //////////////////////////

            ///////////////////////// Facade
            //MortgageFacade mortgage = new MortgageFacade();

            //// Evaluate mortgage eligibility for customer
            //Customer customer = new Customer("Ann McKinsey");
            //bool eligible = mortgage.IsEligible(customer, 125000);

            //Console.WriteLine("\n" + customer.Name +
            //    " has been " + (eligible ? "Approved" : "Rejected"));
            ///////////////////////

            ///////////////////////// ProxyPattern
            MathProxy proxy = new MathProxy();

            // Do the math
            Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));
            ///////////////////////

            Console.ReadKey();
        }
Example #32
0
        static void Main(string[] args)
        {
            #region 简单工厂模式
            Console.WriteLine("===========简单工厂模式============");
            //Practical01:运算操作,计算时,不依赖具体的运算类,通过OperationFactory获取真正的运算类
            Product_Operation operation01 = Factory_OperationFactory.CreateOperate(OPE.PLUS);
            operation01._NumA = 10;
            operation01._NumB = 5;
            Console.WriteLine(operation01.GetResult());
            Product_Operation operation02 = Factory_OperationFactory.CreateOperate(OPE.DIVIDE);
            operation02._NumA = 10;
            operation02._NumB = 5;
            Console.WriteLine(operation02.GetResult());

            //Parctical01:银行支付
            var payment = PaymentFactory.CreatePayment("ABC");
            Console.WriteLine(payment.Payfor(1));
            #endregion
            #region 抽象工厂模式
            Console.WriteLine("===========抽象工厂模式============");
            //便宜套餐
            Factory_Abstract_IKFCFactory Cheap_Abstract = new Factory_CheapPackage();
            KFCFood Cheap_food = Cheap_Abstract.CreateFood();
            Cheap_food.Display();
            KFCDrink Cheap_Drink = Cheap_Abstract.CreateDrink();
            Cheap_Drink.Display();
            //豪华套餐
            Factory_Abstract_IKFCFactory Luxury_Abstract = new Factory_LuxuryPackage();
            KFCFood Luxury_food = Luxury_Abstract.CreateFood();
            Luxury_food.Display();
            KFCDrink Luxury_Drink = Luxury_Abstract.CreateDrink();
            Luxury_Drink.Display();
            #endregion
            #region 建造者模式
            Console.WriteLine("===========建造者模式============");
            _02Builder_VehicleBuilder builder;
            _04Director_Shop          shop = new _04Director_Shop();

            //产品1:Scooter
            builder = new _03ConcreteBuilder_ScooterBuilder();
            shop.Construct(builder);
            builder.Vehicle.Show();
            //产品2:
            builder = new _03ConcreteBuilder_CarBuilder();
            shop.Construct(builder);
            builder.Vehicle.Show();
            #endregion
            #region 工厂方法模式
            Console.WriteLine("===========工厂方法模式============");
            _01Factory_IKFC IKFCFactory = new _01Factory_IKFC_ChickenFactory();
            //生产鸡腿
            _02KFCFood f_1 = IKFCFactory.CreateFood();
            f_1.Display();
            //+1
            _02KFCFood f_2 = IKFCFactory.CreateFood();
            f_2.Display();
            _02KFCFood f_3 = IKFCFactory.CreateFood();
            f_3.Display();
            #endregion
            #region 原型模式
            Console.WriteLine("===========原型模式============");
            _03ColorManager colormanager = new _03ColorManager();

            colormanager["red"] = new _02Color(255, 0, 0);
            // 个性化对象
            colormanager["peace"] = new _02Color(128, 211, 128);
            //浅clone
            _02Color color1 = colormanager["red"].Clone() as _02Color;
            _02Color color2 = colormanager["peace"].Clone() as _02Color;
            #endregion
            #region 单例模式
            Console.WriteLine("===========单例模式============");
            //单线程环境
            Singleton01 s1 = Singleton01.Instance();
            Singleton01 s2 = Singleton01.Instance();
            if (s1 == s2)
            {
                Console.WriteLine("s1 == s2,单例模式");
            }
            #endregion
            #region 适配器模式
            Console.WriteLine("===========适配器模式============");
            Console.WriteLine("手机:");
            _01ITarget t = new Adapter(new _02Power());
            t.GetPower();
            #endregion
            #region 观察者模式
            Console.WriteLine("===========观察者模式============");
            ConcreteSubject concreteSubject = new ConcreteSubject();
            concreteSubject.Attach(new ConcreteObserver(concreteSubject, "X"));
            concreteSubject.Attach(new ConcreteObserver(concreteSubject, "Y"));
            concreteSubject.Attach(new ConcreteObserver(concreteSubject, "Z"));
            //Subject通过Attach()和Detach()方法添加或删除其所关联的观察者,
            //并通过Notify进行更新,让每个观察者都可以观察到最新的状态
            concreteSubject.SubjectState = "ABC";
            concreteSubject.Notify();
            #endregion
            #region 桥接模式
            Console.WriteLine("===========桥接模式============");
            //首先初始化  _01MakeCoffee 抽象类
            //白牛奶
            _01MakeCoffeeSingleton whiteCoffeeSingleton = new _01MakeCoffeeSingleton(new _01MakeCoffee_WhiteCoffee());

            //中杯
            _02Coffee_MediumCupCoffee mediumWhiteCoffee = new _02Coffee_MediumCupCoffee();
            mediumWhiteCoffee.Make();

            //大杯
            _02Coffee_LargeCupCoffee largeCupWhiteCoffee = new _02Coffee_LargeCupCoffee();
            largeCupWhiteCoffee.Make();

            //黑牛奶
            _01MakeCoffeeSingleton blackCoffeeSingleton = new _01MakeCoffeeSingleton(new _01MakeCoffee_BlackCoffee());
            // 中杯
            _02Coffee_MediumCupCoffee mediumBlackCoffee = new _02Coffee_MediumCupCoffee();
            mediumBlackCoffee.Make();

            // 大杯
            _02Coffee_LargeCupCoffee largeCupBlackCoffee = new _02Coffee_LargeCupCoffee();
            largeCupBlackCoffee.Make();
            #endregion
            #region 组合模式
            Console.WriteLine("===========组合模式============");

            Graphics graphics = new Graphics("全部图形");

            _01Sharp_Circle circle = new _01Sharp_Circle("圆形", 5);
            graphics.Add(circle);
            _01Sharp_Rectangle rectangle = new _01Sharp_Rectangle("矩形", 4, 5);
            graphics.Add(rectangle);
            _01Sharp_Triangle triangle = new _01Sharp_Triangle("三角形", 3, 4, 5);
            graphics.Add(triangle);
            graphics.Display();
            #endregion
            #region 外观模式
            Console.WriteLine("===========外观模式============");
            Facade facade = new Facade();
            facade.MethodA();
            facade.MethodB();
            #endregion
            #region 享元模式
            Console.WriteLine("===========享元模式============");
            int extrinsicstate       = 22;
            FlyweightFactory factory = new FlyweightFactory();

            //获取不同的Flyweigh实例
            _01Flyweight fx = factory.GetFlyweight("X");
            fx.Operation(--extrinsicstate);

            _01Flyweight fy = factory.GetFlyweight("Y");
            fy.Operation(--extrinsicstate);

            _01Flyweight fz = factory.GetFlyweight("Z");
            fz.Operation(--extrinsicstate);

            _01FlyweightUnshared fu = new _01FlyweightUnshared();
            fu.Operation(--extrinsicstate);
            #endregion

            #region 代理模式
            Console.WriteLine("===========代理模式============");
            //创建代理
            MathProxy proxy = new MathProxy();
            // Do the math
            Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
            Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
            Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));
            #endregion
            #region 职责链模式
            Console.WriteLine("===========职责链模式============");
            // 创建职责链
            _01Handler h1 = new ConcreteHandler1();
            _01Handler h2 = new ConcreteHandler2();
            _01Handler h3 = new ConcreteHandler3();

            //successor 继承 自Handler,执行 else if 条件中的successor.HandleRequest(request);
            h1.SetSuccessor(h2);
            h2.SetSuccessor(h3);

            int[] requests = { 2, 5, 14, 22, 18, 3, 27, 20 };
            foreach (int request in requests)
            {
                //else if 条件中的successor.HandleRequest(request);
                //h1中SetSuccessor(h2),h2中SetSuccessor(h3)
                //ConcreteHandler1负责处理的请求范围0~10,
                //ConcreteHandler2负责处理的请求范围10~20,
                //ConcreteHandler3负责处理的请求范围20~30。
                //当请求ConcreteHandler1处理不了,则让ConcreteHandler2处理,
                //如果ConcreteHandler2处理不了,则让ConcreteHandler3处理。
                //依次类推,Client的请求会验证职责链传递下去,直至请求被处理,
                //而Client不要关心到底是谁处理了请求。
                h1.HandleRequest(request);
            }
            #endregion

            #region 命令模式
            Console.WriteLine("===========命令模式============");
            _00Receiver receiver = new _00Receiver();
            //调用invoker调用Receiver的操作,实现Execute方法
            _01Command command = new _01CommandConcrete(receiver);
            //命令的接收者,将命令请求传递给相应的命令对象
            Invoker _invoker = new Invoker(command);
            _invoker.ExcuteCommand();
            #endregion
            Console.Read();
        }
Example #33
0
        static void Main(string[] args)
        {
            AbstractPlatform _platform = configurationPlatform();

            _platform.Paint();
            Console.WriteLine("===========================================================================");
            Console.WriteLine("================================== Stragery ===============================");
            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 JuniorDevSalaryCalculator());
            var juniorTotal       = calculatorContext.Calculate(reports);

            Console.WriteLine($"Total amount for junior salaries is: {juniorTotal}");

            calculatorContext.SetCalculator(new SeniorDevSalaryCalculator());
            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}");

            Console.WriteLine("===========================================================================");
            Console.WriteLine("================================== IoC ===============================");
            BussinessLogic _bussinessLogic = new BussinessLogic();

            _bussinessLogic.Task1();

            Console.WriteLine("===========================================================================");
            Console.WriteLine("================================== Flyweight ===============================");

            // The client code usually creates a bunch of pre-populated
            // flyweights in the initialization stage of the application.
            var factory = new FlyweightFactory(
                new Car {
                Company = "Chevrolet", Model = "Camaro2018", Color = "pink"
            },
                new Car {
                Company = "Mercedes Benz", Model = "C300", Color = "black"
            },
                new Car {
                Company = "Mercedes Benz", Model = "C500", Color = "red"
            },
                new Car {
                Company = "BMW", Model = "M5", Color = "red"
            },
                new Car {
                Company = "BMW", Model = "X6", Color = "white"
            }
                );

            factory.listFlyweights();

            addCarToPoliceDatabase(factory, new Car
            {
                Number  = "CL234IR",
                Owner   = "James Doe",
                Company = "BMW",
                Model   = "M5",
                Color   = "red"
            });

            addCarToPoliceDatabase(factory, new Car
            {
                Number  = "CL234IR",
                Owner   = "James Doe",
                Company = "BMW",
                Model   = "X1",
                Color   = "red"
            });

            factory.listFlyweights();

            Console.WriteLine("===========================================================================");
            Console.WriteLine("================================== Proxy ===============================");

            MathProxy _mathProxy = new MathProxy();

            Console.Write("Input num1 and num2: ");
            var x = Convert.ToDouble(Console.ReadLine());
            var y = Convert.ToDouble(Console.ReadLine());

            Console.WriteLine($"{x} + {y} = {_mathProxy.Add(x, y)}");
            Console.WriteLine($"{x} - {y} = {_mathProxy.Sub(x, y)}");
            Console.WriteLine($"{x} * {y} = {_mathProxy.Mul(x, y)}");
            Console.WriteLine($"{x} / {y} = {_mathProxy.Div(x, y)}");

            Console.WriteLine("===========================================================================");
            Console.WriteLine("================================== ProxyWithBank ===============================");

            Credit _credit = new Credit();
            bool   Income  = false;

            _credit.Cash(400, ref Income);

            Income = true;
            Console.WriteLine($"Income {_credit.Cash(5000000.0, ref Income)} vnd");

            Income = false;
            Console.WriteLine($"Outcome {_credit.Cash(100000.0, ref Income)} vnd");

            _credit.CheckAccount();

            Console.WriteLine("-------------------------------------------------------------------------------");
            Console.WriteLine("----------------------------------- Transfer ----------------------------------");
            Console.WriteLine("----------------------------------- Local -------------------------------------");
            Income = false;
            _credit.LocalTransfer(6000000.0, "VND", "01231111441", "8912121231", ref Income);

            Income = true;
            Console.WriteLine($" Income local: " +
                              $"{_credit.LocalTransfer(700000.0, "VND", "719273981723", "1125412311", ref Income)}");
            _credit.CheckAccount();

            Income = false;
            Console.WriteLine($" Outcome local: " +
                              $"{_credit.LocalTransfer(70000.0, "VND", "719273981723", "1125412311", ref Income)}");
            _credit.CheckAccount();
            Console.WriteLine("----------------------------------- Overcome ----------------------------------");
            Income = true;
            Console.WriteLine($"Income overcome: " +
                              $"{_credit.OvercomeTransfer(500, "USD", "VND", "113311131", "719273981723", ref Income)} VND");
            _credit.CheckAccount();

            Income = false;
            Console.WriteLine($"Outcome overcome TWD: " +
                              $"{_credit.OvercomeTransfer(5000000.0, "VND", "TWD", "719273981723", "115533315441", ref Income)} TWD");
            _credit.CheckAccount();

            Console.WriteLine("================================ CompositePattern =====================================");
            CompositePattern.IEmployee employee_0000 = new Cashier(0, "Thu Tran", 7000000);
            CompositePattern.IEmployee employee_0001 = new Cashier(1, "Khoi Nguyen", 7000000);
            CompositePattern.IEmployee employee_0010 = new BankManager(0, "Ning Chang", 9000000);

            employee_0010.Add(employee_0000);
            employee_0010.Add(employee_0001);
            employee_0010.Print();
            Console.WriteLine("===========================================================================");
            Console.WriteLine("================================== Stragery - Ver2 ===============================");
            SortedList _studentRecords = new SortedList();

            _studentRecords.Add("Samual");
            _studentRecords.Add("Jimmy");
            _studentRecords.Add("Sandra");
            _studentRecords.Add("Vivek");
            _studentRecords.Add("Anna");
            Console.WriteLine("------------------------------------------------------------------------------------");
            _studentRecords.SetSortStrategy(new QuickSort());
            _studentRecords.Sort();
            Console.WriteLine("------------------------------------------------------------------------------------");
            _studentRecords.SetSortStrategy(new ShellSort());
            _studentRecords.Sort();
            Console.WriteLine("------------------------------------------------------------------------------------");
            _studentRecords.SetSortStrategy(new MergeSort());
            _studentRecords.Sort();

            Console.WriteLine("===========================================================================");
            Console.WriteLine("================================== Decorator ===============================");
            Console.WriteLine("-------------------------------------------------------------------------------");
            Book _book0000 = new Book("Worley", "Inside ASP.NET", 10);

            _book0000.Display();
            Console.WriteLine("-------------------------------------------------------------------------------");
            Video _video0000 = new Video("Winifred Hervey", "Steve Harvey Show", 1, 512);

            _video0000.Display();
            Console.WriteLine("-------------------------------------------------------------------------------");
            Borrowable _borrower0000 = new Borrowable(_book0000);

            _borrower0000.BorrowItem("Khoi Nguyen Tan");
            _borrower0000.BorrowItem("Ning Chang");
            Borrowable _borrower0001 = new Borrowable(_video0000);

            _borrower0001.BorrowItem("Thu Tran");
            _borrower0001.BorrowItem("Nguyen Lam Bao Ngoc");

            _borrower0000.Display();
            _borrower0001.Display();

            AlertStateContext stateContext = new AlertStateContext();

            stateContext.alert();
            stateContext.alert();
            stateContext.SetState(new Silent());
            stateContext.alert();
            stateContext.alert();
            stateContext.alert();

            Console.WriteLine("===========================================================================");
            Console.WriteLine("================================== AbstractFactoryVer2 ===============================");
            Console.WriteLine("-------------------------------------------------------------------------------");

            ///client class
            AnimalWorld animalWorld = new AnimalWorld(new AmericaFactory());

            animalWorld.AnimalEatOthers();
            animalWorld = new AnimalWorld(new AfricaFactory());
            animalWorld.AnimalEatOthers();

            Console.WriteLine("===========================================================================");
            Console.WriteLine("================================== Template ===============================");
            Console.WriteLine("-------------------------------------------------------------------------------");

            Game game = new Cricket();

            game.Play();
            game = new Football();
            game.Play();

            DataAccessObject dataAccessObject = new Categories();

            dataAccessObject.Run();
            dataAccessObject = new Products();
            dataAccessObject.Run();

            Console.WriteLine("===========================================================================");
            Console.WriteLine("================================== Adapter ===============================");
            Console.WriteLine("-------------------------------------------------------------------------------");
            var xmlConverter = new XmlConverter();
            var adapter      = new XmlToJsonAdapter(xmlConverter);

            adapter.ConvertXMLToJson();

            Console.WriteLine("===========================================================================");
            Console.WriteLine("================================== Template Ver 3 ===============================");
            Console.WriteLine("-------------------------------------------------------------------------------");

            DAO @object = new Person();

            @object.Connect();
            @object.GetAll();
            @object.Process();
            @object.Disconnect();


            Console.WriteLine("===========================================================================");
            Console.WriteLine("================================== ChainOfReposibility ===============================");
            Console.WriteLine("-------------------------------------------------------------------------------");
            // Setup Chain of Responsibility

            Approver larry = new Director();
            Approver sam   = new VicePresident();
            Approver tammy = new President();

            larry.SetSuccessor(sam);
            sam.SetSuccessor(tammy);

            // Generate and process purchase requests

            Purchase p = new Purchase(2034, 350.00, "Assets");

            larry.ProcessRequest(p);

            p = new Purchase(2035, 32590.10, "Project X");
            larry.ProcessRequest(p);

            p = new Purchase(2036, 122100.00, "Project Y");
            larry.ProcessRequest(p);
        }