Advertisement
Guest User

Untitled

a guest
Jun 24th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.03 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace DotNetDesignPatternDemos.SOLID.OCP
  5. {
  6.     public enum Color
  7.     { Red, Green, Blue }
  8.  
  9.     public enum Size
  10.     { Small, Medium, Large }
  11.  
  12.     public class Product
  13.     {
  14.         public string Name;
  15.         public Color Color;
  16.         public Size Size;
  17.  
  18.         public Product(string name, Color color, Size size)
  19.         {
  20.             Name = name ?? throw new ArgumentNullException(paramName: nameof(name));
  21.             Color = color;
  22.             Size = size;
  23.         }
  24.     }
  25.  
  26.     //so Filter can take different specifications(constraints)
  27.     public interface IProductSpecification
  28.     {
  29.         bool IsSatisfied(Product i);
  30.     }
  31.  
  32.     public class ItemFilter
  33.     {
  34.         public IEnumerable<Product> Filter(IEnumerable<Product> items, IProductSpecification spec)
  35.         {
  36.             foreach (Product item in items)
  37.             {
  38.                 if (spec.IsSatisfied(item))
  39.                 {
  40.                     yield return item;
  41.                 }
  42.             }
  43.         }
  44.     }
  45.  
  46.     public class ColorSpecification : IProductSpecification
  47.     {
  48.         private Color color;
  49.         public ColorSpecification(Color color)
  50.         {
  51.             this.color = color;
  52.         }
  53.  
  54.         public bool IsSatisfied(Product p)
  55.         {
  56.             return this.color == p.Color;
  57.         }
  58.     }
  59.  
  60.  
  61.     public class Demo
  62.     {
  63.         static void Main()
  64.         {
  65.             var apple = new Product("Apple", Color.Green, Size.Small);
  66.             var tree = new Product("Tree", Color.Green, Size.Large);
  67.             var house = new Product("House", Color.Blue, Size.Large);
  68.  
  69.             Product[] products = { apple, tree, house };
  70.             ItemFilter PF = new ItemFilter();
  71.             ColorSpecification GreenOnly = new ColorSpecification(Color.Green);
  72.  
  73.             foreach (Product p in PF.Filter(products, GreenOnly))
  74.             {
  75.                 Console.WriteLine(p.Name);
  76.             }
  77.             Console.ReadKey();
  78.         }
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement