As I have
decided to take a break from writing codes, time for some reading. I am always interested in object oriented
designs, I went back and started to study design patterns again. While I am
reading I always make sure that I understand it properly so that I can make it
easy for remember as I come back again. This time I started to forget what I
have read before, so I thought I am going to write it in a blog so that I can
quickly go through if I wanted to. In this blog I will write about Adapter
pattern in OO design Patterns.
Adapter
Pattern: “Converts the interface of a class into another interface clients
expect. Lets classes work together that couldn’t otherwise because of
incompatible interface.”
Let us try
in a way that we should remember this patterns when we hear the name.
Say, I bought a computer from US but it only
works with the American Socket. Here the plug and a computer is our client only
understands AmericanSocket Interface. But I have a EuropeanSocket Interface. I
build a EuropeanAdapter which takes a EuropeanSocket object.
public interface AmericanSocket {
public void optTwoPins();
public void setPower();
}
public class kitchenSocket implements
AmericanSocket {
public void optTwoPins(){
System.out.println(“I can opt for two
pins”);
}
public void setPower(){
System.out.println(“I can work with
120Volts ”);
}
}
Now here is
EuropeanSocket
public interface EuropeanSocket {
public void optThreePins();
public void setPower();
}
public class studySocket implements
EuropeanSocket {
public void setThreePins(){
System.out.println(“I can opt for three
pins ”);
}
public void setPower(){
System.out.println(“I can work with
240Volts ”);
}
}
Here is the
adapter:
public class
EuropeanAdapter implements AmericanSocket{
EuropeanSocket socket;
public EuropeanAdapter(EuropeanSocket
socket){
this.socket = socket;
}
public void
optTwoPins(){
socket.optThreePins();
}
public void
setPower(){
// use a
transformer to step down the power.
socket.setPower();
}
}
Now test it
public class
AmericanComputer {
public static void main(String[] args){
EuropeanSocket socket = new
StudySocket();
AmericanSocket americansocket = new
EuropeanAdapter(socket);
americansocket.optTwoPins();
americansocket.setPower();
}
}
My computer
works now. My computer plug sees adapter as a American Socket.
No comments:
Post a Comment