Implementing the adapter

Typically when implementing an interface you would have to implement all the methods that exist in that interface. A very good example is the MouseListener in the java Swing. When you need to implement more then one method where as typically you might be catching only one of them. Saying that you would also find a Mouse Adapter provided as well. Some of us use that often. And that is part of the Adapter pattern. It makes life easier for me sometimes.

Adapter a structural pattern will let you adapt to a different environment. The joining between different environment is called Adapter. Thus basically giving others the interface that they expect or vice versa when your program becomes the client.

For example the following class expects that the implementing class should be implementing all three methods.

  1. public interface RecordListener {
  2.  
  3. public void eventPrePerformed(RecordEvent recordEvent);
  4.  
  5. public void eventPerformed(RecordEvent recordEvent);}
  6.  
  7. public void eventPostPerformed(RecordEvent recordEvent);
  8.  
  9. }

So lets say our implementing class is a rude one and only wants to implement one method. What do you do as an API designer. hmmm

Thats where we step in with the Adapter.

  1. public abstract class RecordAdapter implements RecordListener {
  2.  
  3. public void eventPrePerformed(RecordEvent recordEvent) {}
  4. public void eventPerformed(RecordEvent recordEvent) {}
  5. public void eventPostPerformed(RecordEvent recordEvent) {}
  6.  
  7. }
  8.  
  9. public MyAdapterImpl extends RecordAdapter{
  10.  
  11. public void eventPerformed(RecordEvent recordEvent){}
  12.  
  13. }

Now the only thing left to do is use the adapter. And override any method that you might need .

  1. public MyClientClass {
  2.  
  3. public MyClientClass(){
  4.  
  5. this.addRecordListener(new MyAdapterImpl());
  6.  
  7. }
  8.  
  9. }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">