Visitor Pattern
Challenge You are having a list of objects with the following class structure: public class Member { public string Name; public DateTime DateOfBirth; } You need to do an operation of selecting all Member having age greater than 18. One way of the solution is add a new property called IsAboveEighteen and set the value by iterating over the items and comparing with current date. But this requires more processing. We can achieve the same using Visitor pattern by adding a property which operations on the existing properties and returns the value. Definition GoF Definition: "Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates" Implementation Introducing a new property named IsAboveEighteen and in the getter implement the code to read DateOfBirth property to calculate the value. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace VisitorPattern { public class Member { public string Name; public DateTime DateOfBirth; public bool IsAboveEighteen { get { bool result = (DateTime .Now - this.DateOfBirth).TotalDays > 365 * 18; return result; } } } } **************************************** using VisitorPattern; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; namespace VisitorPattern.Test { /// <summary> ///This is a test class for MemberTest and is intended ///to contain all MemberTest Unit Tests ///</summary> [TestClass()] public class MemberTest { private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } /// <summary> ///A test for IsAboveEighteen ///</summary> [ TestMethod()] public void IsAboveEighteenTest() { IList<Member > list = new List<Member >() { new Member () { Name = "N1", DateOfBirth= new DateTime (2000, 1, 1)}, new Member () { Name = "N2", DateOfBirth= new DateTime (2000, 1, 1)}, new Member () { Name = "N3", DateOfBirth= new DateTime (1990, 1, 1)}, new Member () { Name = "N4", DateOfBirth= new DateTime (1980, 1, 1)} }; var selectedList = list.Where(m => m.IsAboveEighteen); foreach (Member member in selectedList) Console.WriteLine(member.Name); Assert.AreEqual(2, selectedList.Count()); } } }
Comments