Design Mode Reading Notes-adapter Mode

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.