Monday, January 3, 2011

Adapter : Design Pattern

- Translates one interface for a class into a compatible interface.

Two Kinds of Adapter Patterns
Object Adapter :  Adapter has reference/instance of  Adaptee
Class Adapter :  Adapter uses Adaptee by subclassing. i.e. Adapter extends both Target and Adaptee.  
                         ( Multiple inheritence not possible in java )


(Below is about Object Adapter)
AC: Target
DC 5 AMP:  Adaptee








public interface AC {
    public void doOp();
}


public class AC5AMP implements AC {
   
    public void doOp() {
        System.out.println("Concrete Target");
    }
}


public class DC5AMP {
   
    public void doOp() {
        System.out.println("Concrete Adaptee");
    }
}


public class AC_ADAPTER implements AC {
    private DC5AMP oldSocket;
   
    public AC_ADAPTER( DC5AMP arg) {
        oldSocket = arg;
    }
   
    public void doOp() {
        oldSocket.doOp();
    }
}


public class Client {
    public static void main( String [] args) {
       
        DC5AMP dcSocket = new DC5AMP();

        AC_ADAPTER ac_socket = new AC_ADAPTER(dcSocket);
        ac_socket.doOp();

    }
}

No comments:

Post a Comment