Java Design Patterns Adapter Patterns Example 1

Introduction

Example for the Adapter pattern

The following code will demonstrate the Adapter by using the class ContactAdapter.

It translates from name written in MyName and MyNameImpl.

It enable the code to satisfy the Contact interface.

import java.io.Serializable;

interface MyName {
   public String getMyFirstName();

   public String getMyLastName();

   public void setMyFirstName(String f);

   public void setMyLastName(String l);
}

class MyNameImpl implements MyName {
   private String myFirstName;
   private String myLastName;

   public MyNameImpl() {
   }/*from w  w  w.jav  a2 s  . c o  m*/

   public MyNameImpl(String f, String l) {
      myFirstName = f;
      myLastName = l;
   }

   public String getMyFirstName() {
      return myFirstName;
   }

   public String getMyLastName() {
      return myLastName;
   }

   public void setMyFirstName(String f) {
      myFirstName = f;
   }

   public void setMyLastName(String l) {
      myLastName = l;
   }

   public String toString() {
      return getMyFirstName() + " " + getMyLastName();
   }
}

interface Contact extends Serializable {

   public String getFirstName();

   public String getLastName();

   public void setFirstName(String newFirstName);

   public void setLastName(String newLastName);
}

class ContactAdapter implements Contact {
   private MyName contact;

   public ContactAdapter() {
      contact = new MyNameImpl();
   }

   public ContactAdapter(MyName newContact) {
      contact = newContact;
   }

   public String getFirstName() {
      return contact.getMyFirstName();
   }

   public String getLastName() {
      return contact.getMyLastName();
   }

   public void setContact(MyName newContact) {
      contact = newContact;
   }

   public void setFirstName(String newTitle) {
      contact.setMyFirstName(newTitle);
   }

   public void setLastName(String newOrganization) {
      contact.setMyLastName(newOrganization);
   }

   public String toString() {
      return contact.toString();
   }
}

public class Main {
   public static void main(String[] arguments) {
      Contact contact = new ContactAdapter();

      contact.setFirstName("CSS");
      contact.setLastName("HTML");

      System.out.println(contact.toString());
   }
}



PreviousNext

Related