It is to convert an interface of a class to another interface that the customer expects, that is, to achieve seamless integration of incompatible classes of the two interfaces.
Similar to the power converter function in life;
For example:
Public interface Duck {
Public void quack ();
Public void fly ();
}
Public interface Turkey {
Public void gobble ();
Public void fly ();
}
Public class WildTurkey implements Turkey {
Public void gobble (){
System. out. println ("Gobble gobble ");
}
Public void fly (){
System. out. println ("I'm flying a short distance ");
}
}
Now we use Turkey to disguise Duck.
Public class DuckAdapter implements Turkey {
Duck duck;
Random rand;
Public DuckAdapter (Duck duck ){
This. duck = duck;
Rand = new Random ();
}
Public void gobble (){
Duck. quack ();
}
Public void fly (){
If (rand. nextInt (5) = 0 ){
Duck. fly ();
}
}
}
Public class MallardDuck implements Duck {
Public void quack (){
System. out. println ("Quack ");
}
Public void fly (){
System. out. println ("I'm flying ");
}
}
Public class DuckTestDrive {
Public static void main (String [] args ){
MallardDuck duck = new MallardDuck ();
WildTurkey turkey = new WildTurkey ();
Duck turkeyAdapter = new TurkeyAdapter (turkey );
System. out. println ("The Turkey says ...");
Turkey. gobble ();
Turkey. fly ();
}
This article is from the "Qingfeng" blog