Introduction:
Sometimes you have set of classes with different interfaces and you want to call logic on those classes in a consistent way. Adapter design pattern solve this issue, by providing a technique (best practice) to wrap those classes somehow to make it easy to deal with this set of classes. Also Adapter is responsible of data transformation between heterogeneous interfaces .
The main benefits from Adapter Design pattern is letting classes work together that could not otherwise because of incompatible interfaces.
class Program { static void Main(string[] args) { PersonBase p1 = new GoodPerson(“111111”); PersonBase p2 = new GoodPerson(“222222”); PersonBase p3 = new GoodPerson(“333333”); p1.Display(); p2.Display(); p3.Display(); Console.ReadKey(); } } class PersonDataBank { //Lagecy APIs public float GetTall(string uniqueId) { switch (uniqueId) { case “111111”: return 100f; case “222222”: return 102f; case “333333”: return 103f; default: return 150f; } } public DateTime GetDateOfBith(string uniqueId) { switch (uniqueId) { case “111111”: return DateTime.Parse(“1/1/2000”); ; case “222222”: return DateTime.Parse(“1/1/2001”); ; case “333333”: return DateTime.Parse(“1/1/2002”); ; default: return DateTime.Parse(“1/1/2003”); ; } } public string GetBirthPlace(string uniqueId) { switch (uniqueId) { case “111111”: return “USA,Los Angeles”; case “222222”: return “USA,SD”; case “333333”: return “USA,LV”; default: return “USA,WA”; } } } class PersonBase { public float Tall {get;set;} public DateTime DateOfBirth {get;set;} public string BithPlace {get;set;} protected string uniqueId { get; set; } public PersonBase(string uniqueId) { this.uniqueId = uniqueId; } public virtual void Display() { Console.WriteLine(“\nPerson: {0} “, this.uniqueId); } } class GoodPerson: PersonBase { public GoodPerson(string uniqueId) :base(uniqueId) { } public override void Display() { PersonDataBank bank = new PersonDataBank(); base.DateOfBirth = bank.GetDateOfBith(base.uniqueId); base.BithPlace = bank.GetBirthPlace(base.uniqueId); base.Tall = bank.GetTall(base.uniqueId); base.Display(); Console.WriteLine(” DOB: {0}”, DateOfBirth); Console.WriteLine(” Birth Place : {0}”, BithPlace); Console.WriteLine(” Tall: {0}”, Tall); Console.WriteLine(“=====================”); } } |