Adapter Pattern
Definition-Converts the interface of a class into another interface clients expect. Lets classes work together that couldn’t otherwise because of incompatible interfaces.
How to use?
1. The client makes a request to the adapter by calling a method on it using the target interface.
2. The Adapter translates that request into one or more calls on the adaptee(target objects proceeding requests) using the Adaptee interface.
3. The client receives the results of the call and never knows there is an adapter doing translation.
How to implement this approach (runtime behavior)?
Advantage: decouple the client from implemented interface, and if we expect the interface to change over time, the adapter encapsulates that change so that the client doesn’t have to be modified each time.
Example:Notebook and its ACPower Voltage
... {
public int getPower();
}
class PowerAdapter implements power // like a transformer
... {
AcPower ac;
public PowerAdapter(AcPower ac)
...{
this.ac = ac;
}
public int getPower()
...{
return ac.getACPowerVolt_110();
}
}
class PowerInChina implements power
... {
public int getPower()
...{
return 220;
}
}
class AcPower ... {
public int getACPowerVolt_110()
...{
return 110;
}
}
class NoteBook
... {
power P;
String Name;
public NoteBook(String name)
...{
this.Name = name;
}
public void SetPower(power p)
...{
this.P = p;
}
public void DisplayVoltage()
...{
System.out.println("NoteBook:"+this.Name);
System.out.println("Voltage needed is:"+P.getPower());
}
}
public class Main ... {
public static void main(String[] args) ...{
// TODO Auto-generated method stub
AcPower powerInEurope = new AcPower();
power powerInChina=new PowerInChina();
power powerAdapter=new PowerAdapter(powerInEurope);
NoteBook noteBook1=new NoteBook("buy from China,now use in China");
NoteBook noteBook2=new NoteBook("buy from Europe,now use in China(");
noteBook1.SetPower(powerInChina);
noteBook2.SetPower(powerAdapter);
noteBook1.DisplayVoltage();
noteBook2.DisplayVoltage();
}
}
//If u have anything interesting, pls contact with me. QQ:95491590