public void ExpressionIsEvaluated(int value, bool expectedIsSatisfied)
        {
            // Arrange
            var is42 = new ExpressionSpecification <int>(i => i == 42);

            // Act
            var result = is42.IsSatisfiedBy(value);

            // Assert
            result.Should().Be(expectedIsSatisfied);
        }
예제 #2
0
            public void TrueExpression_ReturnExpectedResultObject()
            {
                var expected = new SpecificationResult("ExpressionSpecification<Object>");
                Expression <Func <object, bool> > expression = candidate => true;
                var sut = new ExpressionSpecification <object>(expression);

                var overall = sut.IsSatisfiedBy(new object(), out var result);

                Assert.True(overall);
                Assert.Equal(expected, result, new SpecificationResultComparer());
            }
예제 #3
0
            public void FalseExpression_ReturnExpectedResultObject()
            {
                var dum = new object();
                Expression <Func <object, bool> > expression = candidate => false;
                var expected = new SpecificationResult(false, "ExpressionSpecification<Object>+Failed",
                                                       new FailedSpecification(typeof(ExpressionSpecification <object>), new Dictionary <string, object>
                {
                    { "Expression", expression }
                }, dum, "Specification doesn't meet expression: [candidate => False]"));
                var sut = new ExpressionSpecification <object>(expression);

                var overall = sut.IsSatisfiedBy(dum, out var result);

                Assert.False(overall);
                Assert.Equal(expected, result, new SpecificationResultComparer());
            }
예제 #4
0
        public static void Main()
        {
            var someBookstore = new Bookstore("Shakespeare and Company");

            var witchesAbroad = new Book("Witches abroad", Genre.Fantasy, 301);
            someBookstore.Add(witchesAbroad);
            var hatFullOfSky = new Book("Hat full of sky", Genre.Fantasy, 310);
            someBookstore.Add(hatFullOfSky);
            var gameOfThrones = new Book("Game of thrones", Genre.Fantasy, 900);
            someBookstore.Add(gameOfThrones);
            var deathOnTheNile = new Book("Death on the Nile", Genre.Crime, 400);
            someBookstore.Add(deathOnTheNile);
            var historyOfTheBalkans = new Book("History of the Balkans", Genre.History, 1120);
            someBookstore.Add(historyOfTheBalkans);

            Console.WriteLine(someBookstore);

            var ruleOnlyFantasy = new ExpressionSpecification<Book>(b => b.Genre == Genre.Fantasy);
            var ruleLargeBooks = new ExpressionSpecification<Book>(b => b.Pages > 1000);
            var rulePagesBelow500 = new ExpressionSpecification<Book>(b => b.Pages < 500);
            var ruleFantasyOrLargeBooks = ruleOnlyFantasy.Or(ruleLargeBooks);

            var allBooks = someBookstore.All();

            var largeBooks = allBooks.FindAll(b => ruleLargeBooks.IsSatisfiedBy(b));
            Console.WriteLine("Large books:");
            foreach (var book in largeBooks)
            {
                Console.WriteLine(book);
            }

            Console.WriteLine();

            var fantasyAndLargeBooks = allBooks.FindAll(b => ruleFantasyOrLargeBooks.IsSatisfiedBy(b));
            Console.WriteLine("Fantasy and large books:");
            foreach (var book in fantasyAndLargeBooks)
            {
                Console.WriteLine(book);
            }

            Console.WriteLine();
        }
예제 #5
0
        public static void Main(string[] args)
        {
            var mobiles = new List<Mobile>() {
                new Mobile(MobileBrand.Apple, MobileType.Smart),
                new Mobile(MobileBrand.Samsung, MobileType.Smart),
                new Mobile(MobileBrand.Samsung, MobileType.Basic)
            };

            var smartSpecification = new ExpressionSpecification<Mobile>(mobile => mobile.Type == MobileType.Smart);
            var appleSpecification = new ExpressionSpecification<Mobile>(mobile => mobile.Brand == MobileBrand.Apple);
            // find all smart mobiles;
            var smartMobiles = mobiles.FindAll(mobile => smartSpecification.IsSatisfiedBy(mobile));
            // find all apple smart mobiles;
            var andSpecification = new AndSpecification<Mobile>(smartSpecification, appleSpecification);
            var appleSmartMobiles = mobiles.FindAll(mobile => andSpecification.IsSatisfiedBy(mobile));

            Console.WriteLine("Hello World!");

            Console.ReadKey();
        }
예제 #6
0
        private List <EntityError> ValidateCountry(Country country)
        {
            List <EntityError> errors = new List <EntityError>();
            var isNameIsNotEmpty      = new ExpressionSpecification <Country>(c => !string.IsNullOrEmpty(c.Name))
                                        .And(new ExpressionSpecification <Country>(c => !string.IsNullOrEmpty(c.Code)));

            if (!isNameIsNotEmpty.IsSatisfiedBy(country))
            {
                throw new ArgumentNullException("Name");
            }

            var isNameOrCodeExistSpecification = new ExpressionSpecification <Country>(c => c.Id != country.Id &&
                                                                                       (c.Name.ToLower() == country.Name.ToLower() || c.Code.ToLower() == country.Code.ToLower()));

            if (_unitOfWork.CountryRepository.Find(isNameOrCodeExistSpecification).Any())
            {
                errors.Add(new EntityError("Country Name or Code already exist", ValidationErrorTypes.DuplicatedValue));
            }

            return(errors);
        }
예제 #7
0
        static void Main(string[] args)
        {
            // Person list
            var people = new List <Person> {
                new Person(Guid.NewGuid(), "Douglas 1", new Email("*****@*****.**"), new Category(2, "Partner")),
                new Person(Guid.NewGuid(), "Douglas 2", new Email("*****@*****.**"), new Category(1, "Customer")),
                new Person(Guid.NewGuid(), "Douglas 3", new Email("*****@*****.**"), new Category(2, "Partner")),
                new Person(Guid.NewGuid(), "Douglas 4", new Email("douglas4_gmail.com"), new Category(1, "Customer")),
                new Person(Guid.NewGuid(), "Douglas 5", new Email("*****@*****.**"), new Category(1, "Customer")),
                new Person(Guid.NewGuid(), "Douglas 6", new Email("*****@*****.**"), new Category(1, "Customer")),
                new Person(Guid.NewGuid(), "Douglas 7", new Email("*****@*****.**"), null)
            };

            Console.WriteLine(":: ALL PEOPLE ::");

            foreach (var item in people)
            {
                Console.WriteLine(item.PersonId + " | " + item.Name + " | " + item?.Email?.Address + " | " + item.Category?.Description);
            }

            // Specifications usages

            Console.WriteLine("");
            Console.WriteLine(":: CUSTOMER ::");

            ISpecification <Person> personCustomersSpecification = new PersonCustomerSpecification <Person>();

            var customer = people.FindAll(x => personCustomersSpecification.IsSatisfiedBy(x));

            foreach (var item in customer)
            {
                Console.WriteLine(item.PersonId + " | " + item.Name + " | " + item.Email.Address + " | " + item.Category?.Description);
            }

            Console.WriteLine("");
            Console.WriteLine(":: PARTNER ::");

            ISpecification <Person> partnerSpecification = new ExpressionSpecification <Person>(x => x.Category?.CategoryId == 2);

            var partners = people.FindAll(x => partnerSpecification.IsSatisfiedBy(x));

            foreach (var item in partners)
            {
                Console.WriteLine(item.PersonId + " | " + item.Name + " | " + item.Email.Address + " | " + item.Category?.Description);
            }

            Console.WriteLine("");
            Console.WriteLine(":: WITHOUT CATEGORY ::");

            ISpecification <Person> nullSpecification = new ExpressionSpecification <Person>(x => x.Category == null);

            var nullCategory = people.FindAll(x => nullSpecification.IsSatisfiedBy(x));

            foreach (var item in nullCategory)
            {
                Console.WriteLine(item.PersonId + " | " + item.Name + " | " + item.Email.Address + " | " + item.Category?.Description);
            }

            Console.WriteLine("");
            Console.WriteLine(":: WITH AND WITHOUT CATEGORY ::");

            ISpecification <Person> customersSpecification = new ExpressionSpecification <Person>(x => x.Category?.CategoryId == 1);
            var allWithCategorySpecification = customersSpecification.Or(partnerSpecification);
            var includeNull = allWithCategorySpecification.Or(nullSpecification);

            var allAndNullCategory = people.FindAll(x => includeNull.IsSatisfiedBy(x));

            foreach (var item in allAndNullCategory)
            {
                Console.WriteLine(item.PersonId + " | " + item.Name + " | " + item.Email.Address + " | " + item.Category?.Description);
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("");
            Console.WriteLine(":: ALL VALID ::");

            ISpecification <Person> validSpecification = new PersonValidSpecification <Person>();

            var validPeople = people.Where(x => validSpecification.IsSatisfiedBy(x));

            foreach (var item in validPeople)
            {
                Console.WriteLine(item.PersonId + " | " + item.Name + " | " + item.Email.Address + " | " + item.Category?.Description);
            }

            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("");
            Console.WriteLine(":: VALID CUSTOMERS ::");

            var validCustomers = people.Where(x => validSpecification.IsSatisfiedBy(x) && customersSpecification.IsSatisfiedBy(x));

            foreach (var item in validCustomers)
            {
                Console.WriteLine(item.PersonId + " | " + item.Name + " | " + item.Email.Address + " | " + item.Category?.Description);
            }

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("");
            Console.WriteLine(":: VALID PARTNERS ::");

            var validPartners = people.Where(x => validSpecification.IsSatisfiedBy(x) && partnerSpecification.IsSatisfiedBy(x));

            foreach (var item in validPartners)
            {
                Console.WriteLine(item.PersonId + " | " + item.Name + " | " + item.Email.Address + " | " + item.Category?.Description);
            }

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("");
            Console.WriteLine(":: INVALID ::");

            var invalidPeople = people.Where(x => !validSpecification.IsSatisfiedBy(x));

            foreach (var item in invalidPeople)
            {
                Console.WriteLine(item.PersonId + " | " + item.Name + " | " + item.Email.Address + " | " + item.Category?.Description);
            }

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("");
            Console.WriteLine(":: ISVALID ::");

            var isvalidPeople = people.Where(x => x.IsValid());

            foreach (var item in isvalidPeople)
            {
                Console.WriteLine(item.PersonId + " | " + item.Name + " | " + item.Email.Address + " | " + item.Category?.Description);
            }

            Console.ReadKey();
        }
 public void ExpressionSpecification_IsSatisfiedBy_Success()
 {
     var spec = new ExpressionSpecification<Product>(x => x.Id == 10);
     Assert.True(spec.IsSatisfiedBy(_product));
 }
예제 #9
0
        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("==========时间格式化-本地文化============");
        }
 public void IsSatisfiedByTestCase1()
 {
     var target = new ExpressionSpecification<String>( x => x.Length > 5 );
     var actual = target.IsSatisfiedBy( "123456" );
     Assert.IsTrue( actual );
 }
예제 #11
0
        public void ExpressionSpecification_IsSatisfiedBy_Success()
        {
            var spec = new ExpressionSpecification <Product>(x => x.Id == 10);

            Assert.True(spec.IsSatisfiedBy(_product));
        }