Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- namespace DotNetDesignPatternDemos.SOLID.OCP
- {
- public enum Color
- { Red, Green, Blue }
- public enum Size
- { Small, Medium, Large }
- public class Product
- {
- public string Name;
- public Color Color;
- public Size Size;
- public Product(string name, Color color, Size size)
- {
- Name = name ?? throw new ArgumentNullException(paramName: nameof(name));
- Color = color;
- Size = size;
- }
- }
- //so Filter can take different specifications(constraints)
- public interface IProductSpecification
- {
- bool IsSatisfied(Product i);
- }
- public class ItemFilter
- {
- public IEnumerable<Product> Filter(IEnumerable<Product> items, IProductSpecification spec)
- {
- foreach (Product item in items)
- {
- if (spec.IsSatisfied(item))
- {
- yield return item;
- }
- }
- }
- }
- public class ColorSpecification : IProductSpecification
- {
- private Color color;
- public ColorSpecification(Color color)
- {
- this.color = color;
- }
- public bool IsSatisfied(Product p)
- {
- return this.color == p.Color;
- }
- }
- public class Demo
- {
- static void Main()
- {
- var apple = new Product("Apple", Color.Green, Size.Small);
- var tree = new Product("Tree", Color.Green, Size.Large);
- var house = new Product("House", Color.Blue, Size.Large);
- Product[] products = { apple, tree, house };
- ItemFilter PF = new ItemFilter();
- ColorSpecification GreenOnly = new ColorSpecification(Color.Green);
- foreach (Product p in PF.Filter(products, GreenOnly))
- {
- Console.WriteLine(p.Name);
- }
- Console.ReadKey();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement