Thursday, May 10, 2012

Design Pattern Study Notes 2 - Adapter














Problem:
If want to reuse the existing class, but its interface does not meet the new requirement.

Solution:
Adapter pattern.

1) This is new interface we want to implement.
======================== Target.java ====================

package test.pattern.adapter;

public interface Target {

public void methodA();
public void methodB();
}

2) This is the existing class we have.
======================= Adaptee.java ================

package test.pattern.adapter;

public class Adaptee {

public void methodA() {
System.out.println("it is method A.");
}
}

3) This is an adapter class to implement above new interface Target.java
=================== Adapter.java =====================
package test.pattern.adapter;

public class Adapter extends Adaptee implements Target {

public void methodB() {
System.out.println("it is method B.");
}

}

4) This is another adapter to implement above new interface Target.java
=================== Adapter2.java ====================
package test.pattern.adapter;

public class Adapter2 implements Target {

private Adaptee adaptee;

public Adapter2(Adaptee adaptee) {
this.adaptee = adaptee;
}

public void methodA() {
this.adaptee.methodA();
}

public void methodB() {
System.out.println("this is method B.");
}

}

5) test class
============== Client.java ======================
package test.pattern.adapter;

public class Client {

public static void main(String[] args) {
Target adapter = new Adapter();
adapter.methodA();
adapter.methodB();

Adaptee adaptee = new Adaptee();
Target adapter2 = new Adapter2(adaptee);
adapter2.methodA();
adapter2.methodB();
}

}

This is output:
it is method A.
it is method B.
it is method A.
this is method B.



No comments:

Post a Comment