Verwendung für das Adaptor Pattern findet man für die Erweiterung einer Schnittstelle z.B. eines Drittanbieters, hier Dient der Adapter als Hülle für das Kapseln eigener Funktionen.
Als Beispiel habe ich 2 Klassen angelegt, die mir als Schnitstelle dienen. Die Person ist meine Adapterklasse und implementiert meine Erweiterung
Die Basisklassen Laptop.cs und SmartPhone.cs
namespace AdaptorPattern
{
interface ILaptop
{
string ShowModel();
}
class Acer : ILaptop
{
public string ShowModel()
{
return "Acer";
}
}
class Dell : ILaptop
{
public string ShowModel()
{
return "Dell";
}
}
class Lenovo : ILaptop
{
public string ShowModel()
{
return "Lenovo";
}
}
}
namespace AdaptorPattern
{
interface ISmartPhone
{
string ShowModel();
}
class Nokia : ISmartPhone
{
public string ShowModel()
{
return "Nokia";
}
}
class Samsung : ISmartPhone
{
public string ShowModel()
{
return "Samsung";
}
}
class Apple : ISmartPhone
{
public string ShowModel()
{
return "Apple";
}
}
class BlackBlarry : ISmartPhone
{
public string ShowModel()
{
return "BlackBarry";
}
}
}
Die Adapterklasse Person.cs
namespace AdaptorPattern
{ enum pName
{
Gerrit = 1,
Max = 2,
Moritz = 3,
Fritz=4
}
class Person
{
public string Name { get; set; }
public Person()
{
}
public Person(pName name)
{
Name = name.ToString("g") + " sagt: ";
}
public string SwitchOn(ILaptop obj)
{
return Name + LaptopAdaptor.ShowModel(obj);
}
public string SwitchOn(ISmartPhone obj)
{
return Name + SmartPhoneAdaptor.ShowModel(obj);
}
}
class SmartPhoneAdaptor : ISmartPhone
{
const string Typ = "Mein SmartPhone ist von {0} und ich mache das Gerät an.";
public string ShowModel()
{
return null;
}
public static string ShowModel(ISmartPhone obj)
{
return string.Format(Typ, obj.ShowModel());
}
}
class LaptopAdaptor : ILaptop
{
const string Typ = "Mein Laptop ist von {0} und ich mache das Gerät an.";
public string ShowModel()
{
return null;
}
public static string ShowModel(ILaptop obj)
{
return string.Format(Typ, obj.ShowModel());
}
}
}
Die Programmklasse
using System;
using AdaptorPattern;
namespace AdpatorDesign
{
class Program
{
static void Main(string[] args)
{
Person p = new Person();
Person p2 = new Person(pName.Max);
Person p3 = new Person(pName.Moritz);
Person p4 = new Person(pName.Gerrit);
Person p5 = new Person(pName.Fritz);
Console.WriteLine(p.SwitchOn(new Acer()));
Console.WriteLine(p2.SwitchOn(new Dell()));
Console.WriteLine(p3.SwitchOn(new Lenovo()));
Console.WriteLine(p4.SwitchOn(new Nokia()));
Console.WriteLine(p5.SwitchOn(new BlackBlarry()));
Console.ReadLine();
}
}
}
Und so sieht es aus:
