Design Pattern adapter-telephone
A friend told me his phone number a few days ago. I copied it to a small piece of paper and put it in a book, later, I did not expect my wife to mail this book to his younger brother. I had no way to contact my friends when I had something important. The book has been mailed, which cannot be changed. It is necessary to call a friend to say something important. These cannot be transferred with my will. What should I do? Fortunately, there is a modern communication tool-Telephone. Can I call my uncle and ask him to tell me why?
Let's get started.
1. Here, we first define a postedbook class:
Public class postedbook {
// Obtain the phone number from the book
Public void gettelcodefrombook (){
System. Out. println ("Get the phone number! ");
}
}
2. Define another teltofriend class:
Public class teltofriend {
Public void telsaything (){
System. Out. println ("important thing! ");
}
}
3. Define the telphone class:
Public class telphone extends teltofriend {
Private postedbook;
Public telphone (postedbook) {// call your email
This. postedbook = postedbook;
}
Public void gettelcode () {// obtain the phone number from the email address book
Postedbook. gettelcodefrombook ();
}
}
4. Compile the test class:
Public class test {
Public static void main (string ARGs []) {
Postedbook = new postedbook (); // the book to be mailed
Telphone = new telphone (postedbook );
Telphone. gettelcode (); // get a friend's phone number
Telphone. telsaything (); // tell friends about important things
}
}
5. Description:
A: The adapter mode is used together to combine two irrelevant classes. In this example, the mail book and the phone call to a friend are two irrelevant tasks, it is because of a phone number that can be associated with them, but the premise for obtaining this number is that I have to make a call first, so I have achieved my goal through the phone.
B: By calling the coordination class, I got the desired phone number and talked to my friends.