Beispiel #1
0
        public void Calculate_OnLowSalary_NoTaxes(int salary)
        {
            var result = _salaryCalculator.Calculate(new Input
            {
                Salary = salary
            });

            Assert.AreEqual(0, result.Tax);
            Assert.AreEqual(0, result.Super);
            Assert.AreEqual(Math.Round(salary / 12d, MidpointRounding.AwayFromZero), result.Gross);
            Assert.AreEqual(result.Gross, result.Net);
        }
Beispiel #2
0
        public void 算薪水()
        {
            var salaryFormula = new SalaryFormula();
            var test          = new SalaryCalculator(salaryFormula);

            test.Calculate(10, 10, 0);
        }
Beispiel #3
0
        public void ShouldGive10PercentDiscountIfSalaryIsLessThanLimit()
        {
            var salary    = 3000m;
            var developer = new Employee(name: "Fleta Balistreri", salary, Role.Developer);

            Assert.AreEqual(2700m, SalaryCalculator.Calculate(developer));
        }
        public void Calculate_WhenGrossPackageIsValid_ReturnsCorrectSalary(decimal grossPackage,
                                                                           decimal expectedSuperannuation, decimal expectedTaxableIncome, decimal expectedNetIncome,
                                                                           decimal expectedPayPacket)
        {
            //Arrange
            var sc = new ServiceContainer();

            sc.Register <SalaryDetails>((c) =>
            {
                var medicareLevyDeduction     = c.GetInstance <MedicareLevyDeduction>();
                var budgetRepairLevyDeduction = c.GetInstance <BudgetRepairLevyDeduction>();
                var incomeTaxDeduction        = c.GetInstance <IncomeTaxDeduction>();

                return(new SalaryDetails(medicareLevyDeduction, budgetRepairLevyDeduction, incomeTaxDeduction));
            }, new PerContainerLifetime());
            sc.Register <MedicareLevyDeduction>();
            sc.Register <BudgetRepairLevyDeduction>();
            sc.Register <IncomeTaxDeduction>();

            var sut = new SalaryCalculator(sc);
            //Act
            var salaryDetails = sut.Calculate(grossPackage, PayFrequency.Monthly);

            //Assert
            salaryDetails.Superannuation.Should().Be(expectedSuperannuation);
            salaryDetails.TaxableIncome.Should().Be(expectedTaxableIncome);
            salaryDetails.NetIncome.Should().Be(expectedNetIncome);
            salaryDetails.PayPacket.Should().Be(expectedPayPacket);
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            //一般員工(以Container方式實現DI)
            using (IUnityContainer container = new UnityContainer())
            {
                UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                //只有container不同
                section.Configure(container, "containerEmployee");
                //其他code完全相同
                SalaryCalculator SC     = container.Resolve <SalaryCalculator>();
                float            amount = SC.Calculate(8 * 19, 200, 8);
                Console.Write("\nSalaryFormula--->amount:" + amount);
                Console.ReadKey();
            }

            //老闆
            using (IUnityContainer container = new UnityContainer())
            {
                UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                //只有container不同
                section.Configure(container, "containerBoss");
                //其他code完全相同
                SalaryCalculator SC     = container.Resolve <SalaryCalculator>();
                float            amount = SC.Calculate(8 * 19, 200, 8);
                Console.Write("\nSalaryFormula--->amount:" + amount);
                Console.ReadKey();
            }
        }
Beispiel #6
0
        private void btnSalaryCalculator_Click(object sender, RoutedEventArgs e)
        {
            using (var context = new CupOfCoffeeContext())
            {
                try
                {
                    var pdfFile = new PdfFile();
                    pdfFile.filename = "..\\..\\..\\PDFReport\\employee-sallaries.pdf";
                    pdfFile.title    = "Report: Employees sallaries";
                    pdfFile.data     = SalaryCalculator.Calculate(context);

                    PdfCreator.Create(pdfFile);

                    SalaryRecorder.Insert(pdfFile.data, context);

                    //var pathToAcroRd32 = Environment.GetEnvironmentVariable("ProgramFiles") + @"\Adobe\Reader 11.0\Reader\AcroRd32.exe";
                    //var adobeInfo = new ProcessStartInfo(pathToAcroRd32, pdfFile.filename);

                    MessageBox.Show("The report for employees was successfully generated!",
                                    "Generated successfully",
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Information);

                    Process.Start(pdfFile.filename);
                }
                catch (Exception)
                {
                    MessageBox.Show("Cannot generate the report for employees!",
                                    "Generation failed",
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                }
            }
        }
Beispiel #7
0
        public void Calculate_WhenProvidedNull_ReturnsEmpty()
        {
            var calculator = new SalaryCalculator();

            var result = calculator.Calculate(null);

            result.ShouldBeEmpty();
        }
 public IActionResult GetWithSalary()
 {
     return(Ok(m_context.Employees.Select(
                   x => SalaryCalculator.Calculate(x,
                                                   m_context.BaseSalaries.FirstOrDefault(y =>
                                                                                         y.Position == x.Position && y.ExperienceFrom <= x.ExperienceYears && y.ExperienceTo >= x.ExperienceYears)))
               ));
 }
        public void ShouldObtainTheJuniorsTotalSalary()
        {
            var calculatorContext = new SalaryCalculator(new JuniorDevSalaryCalculator());

            var juniorsTotalSalary = calculatorContext.Calculate(_reports);

            juniorsTotalSalary.Should().Be(5830);
        }
        public void ShouldObtainTheSeniorsTotalSalary()
        {
            var calculatorContext = new SalaryCalculator(new SeniorDevSalaryCalculator());

            var seniorsTotalSalary = calculatorContext.Calculate(_reports);

            seniorsTotalSalary.Should().Be(10926);
        }
Beispiel #11
0
        public void ShouldGive15PercentDiscountIfSalaryIsLessThanLimit()
        {
            var salary = 2500m;
            var dba    = new Employee(name: "Fleta Balistreri", salary, Role.DBA);
            var tester = new Employee(name: "Fleta Balistreri", salary, Role.Tester);

            Assert.AreEqual(2125m, SalaryCalculator.Calculate(dba));
            Assert.AreEqual(2125m, SalaryCalculator.Calculate(tester));
        }
Beispiel #12
0
        public void Calculate_WhenProvidedInvalidEmployee_ReturnsEmpty()
        {
            var employee   = new Employee();
            var calculator = new SalaryCalculator();

            var result = calculator.Calculate(employee);

            employee.IsValid().ShouldBeFalse();
            result.ShouldBeEmpty();
        }
Beispiel #13
0
        public void ExpirienceDoesNotMatch()
        {
            var employee = new Employee()
            {
                ExperienceYears = 100, Position = "NotTech", SatisfactionScore = SatisfactionScore.AboveAverage
            };
            var baseSalary = new BaseSalary()
            {
                ExperienceFrom = 0, ExperienceTo = 1, Position = "Tech", Salary = 1000
            };

            Assert.ThrowsException <ArgumentException>(() => SalaryCalculator.Calculate(employee, baseSalary));
        }
Beispiel #14
0
        public void Calculate_WhenProvidedValidEmployee_ReturnsOneResult()
        {
            var employee = new Employee
            {
                FirstName = "John",
                LastName  = "Smith"
            };
            var calculator = new SalaryCalculator();

            var result = calculator.Calculate(employee);

            result.Count().ShouldEqual(1);
        }
Beispiel #15
0
        public void Satisfied()
        {
            var employee = new Employee()
            {
                ExperienceYears = 1, Position = "Tech", SatisfactionScore = SatisfactionScore.Satisfied
            };
            var baseSalary = new BaseSalary()
            {
                ExperienceFrom = 0, ExperienceTo = 1, Position = "Tech", Salary = 1000
            };

            Assert.AreEqual(1950, SalaryCalculator.Calculate(employee, baseSalary).Salary);
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            //一般員工 SalaryFormula
            SalaryCalculator SC = new SalaryCalculator(new SalaryFormula());
            //注意參數完全相同
            float amount = SC.Calculate(8 * 19, 200, 8);

            Console.Write("\nSalaryFormula--->amount:" + amount);

            //老闆 BossSalaryFormula
            SC = new SalaryCalculator(new BossSalaryFormula());
            //注意參數完全相同
            amount = SC.Calculate(8 * 19, 200, 8); //即便與員工相同
                                                   //但計算出的結果不同
            Console.Write("\nBoss SalaryFormula--->amount:" + amount);
            Console.Write("\n");
            Console.ReadKey();
        }
Beispiel #17
0
        public void Calculate_WhenProvidedValidEmployee_ReturnExpectedValues()
        {
            var expectedPerAnnum     = SalaryCalculator.EmployeeSalaryPerPayPeriod * Constants.NumberOfPayPeriodsPerYear;
            var expectedPerPayPeriod = SalaryCalculator.EmployeeSalaryPerPayPeriod;
            var employee             = new Employee
            {
                FirstName = "John",
                LastName  = "Smith"
            };
            var calculator = new SalaryCalculator();

            var result = calculator.Calculate(employee).FirstOrDefault();

            result.ShouldNotBeNull();
            result.Description.ShouldEqual(SalaryCalculator.Descriptions.EmployeeSalary);
            result.PerAnnum.ShouldEqual(expectedPerAnnum);

            result.PerPayPeriod.All(x => x == expectedPerPayPeriod).ShouldBeTrue();
        }
Beispiel #18
0
        public void BaseSalary_Null()
        {
            var employee = new Employee();

            Assert.ThrowsException <ArgumentNullException>(() => SalaryCalculator.Calculate(employee, null));
        }
Beispiel #19
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);
        }
        static void Main(string[] args)
        {
            // Factory Pattern
            var factory = new AirConditioner().ExecuteCreation(Actions.Cooling, 20);

            factory.Operate();
            //---------------------------------------------------------------------

            //Facted Builder Pattern
            var car = new CarBuilderFacade()
                      .Info
                      .WithColor("Black")
                      .WithNumberOfDoors(4)
                      .WithType("BMW")
                      .Built
                      .AtAddress("Address")
                      .InCity("Alexandria")
                      .Build();

            Console.WriteLine(car.ToString());

            //------------------------------------------------------------------------
            // Composite Pattern
            var phone = new SingleGift("Phone", 256);

            phone.CalculateTotalPrice();


            //composite gift
            var rootBox  = new CompositeGift("RootBox", 0);
            var truckToy = new SingleGift("TruckToy", 289);
            var plainToy = new SingleGift("PlainToy", 587);

            rootBox.Add(truckToy);
            rootBox.Add(plainToy);
            var childBox   = new CompositeGift("ChildBox", 0);
            var soldierToy = new SingleGift("SoldierToy", 200);

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

            Console.WriteLine($"Total price of this composite present is: {rootBox.CalculateTotalPrice()}");
            //-----------------------------------------------------------------------
            // Decorator Pattern
            var regularOrder = new RegularOrder();

            Console.WriteLine(regularOrder.CalculateTotalOrderPrice());
            Console.WriteLine();

            var preOrder = new Preorder();

            Console.WriteLine(preOrder.CalculateTotalOrderPrice());
            Console.WriteLine();

            var premiumPreorder = new PremiumPreorder(preOrder);

            Console.WriteLine(premiumPreorder.CalculateTotalOrderPrice());

            //---------------------------------------------------------------------
            // Strategy Pattern

            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.Read();
        }
        static void Main(string[] args)
        {
            var random = new Random();

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

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

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

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

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

            var productsReport = builder.GetReport();

            Console.WriteLine(productsReport);

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

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

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

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

            Console.WriteLine(emp);

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

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

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

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

            Console.WriteLine(car);

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

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

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

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

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

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

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

            var db1 = SingletonDataContainer.GetInstance;

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

            var db2 = SingletonDataContainer.GetInstance;

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

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

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

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

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

            adapter.ConvertXmlToJson();

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

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

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

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

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

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

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

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

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

            rootBox.CalculateTotalPrice();

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

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

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

            var regularOrder = new RegularOrder();

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

            var preOrder = new PreOrder();

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

            var premiumPreOrder = new PremiumPreOrder(preOrder);

            Console.WriteLine(premiumPreOrder.CalculateTotalOrderPrice());

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            var facade = new Facade.Facade();

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

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

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

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

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

            var grid = new List <IBlock>();

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

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

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

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

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

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

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

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

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

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

            Console.WriteLine(settings.GetConfig());

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

            Console.WriteLine(protectedSettings.GetConfig());

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

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

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

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

            var iterator = numbers.Iterator;

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

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

            // ********* Iterator Pattern Usage: END
        }
Beispiel #22
0
        public void Employee_Null()
        {
            var baseSalary = new BaseSalary();

            Assert.ThrowsException <ArgumentNullException>(() => SalaryCalculator.Calculate(null, baseSalary));
        }