Design Patterns: Object Adapters

An Object Adapters is a wrapper class the wraps an old object that needs data manipulated before the new object can use it, just like you would with a real life object such as an electronic device where main power plugs are different in each country, so you will need a power adapter to plug it in. This post I will demonstrate one type of adapter which is the object adapter, this type of adapter basically contains an instance of the object that needs adapting or also known as the adaptee.

Lets put this into a real word situation where you have an old class called OldPerson which only allows you to set and get a person name by calling a member method called SetFullName() and GetFullName(). In the new system you have a new class called Person which only takes First and Last name as strings. So what do we do you ask, we need to write a PersonAdapter class!

The Person class implements the IPersion interface which contains four methods, SetFirstName(), GetFirstName(), SetLastName() and GetLastName(). In PersonAdapter class we will implement the IPerson interface so that we have the same implementation as Person class.

public class PersonAdapter : IPerson
{
   // code here.
}

In the PersonAdapter class constructer we are going to pass the OldPerson object as a parameter and retrieve the person’s full name. By using the string’s Split method we can separate the first and last name and assign it to the private member variables called firstName and LastName.

public PersonAdapter (OldPerson oldPerson)
{
    this.oldPerson = oldPerson;
    var fullname = this.oldPerson.GetFullName();
    this.firstName = fullname.Split(' ')[0];
    this.lastName = fullname.Split(' ')[1];
}

(more…)

Shares