Adapter mode

1. Concept:  
Transform the interface of a class into another interface expected by the client, so that two classes that cannot work together due to interface mismatch can work together.

(It is to combine the methods of two classes so that they can be used in one class!)
2. Two forms 

a. Adapter mode for classes b. Adapter mode for objects

http://www.iteye.com/topic/339198

http://www.iteye.com/topic/74417

 

1. Concept: 
The Adapter Pattern transforms the interface of a class into another interface expected by the client, so that two classes that cannot work together due to interface mismatch can work together. 
2. Two forms 
a. Adapter mode for classes b. Adapter mode for objects 


3. Simulation problem: 
Now suppose that our program has designed the interface Request interface, but now there is a special interface SpecificRequst that can better complete our functions, but it does not match our existing Request interface. So how do we make them work together? See the example below: 


3. Example 1: a. Adapter mode  of class (inherit class, implement interface)

target role:

  1. public interface Target {  
  2.     public void request();  
  3. }  


Source role:

  1. public class Adaptee {  
  2.     public void specificRequest(){  
  3.         System.out.println( "Achieve the desired function" );  
  4.     }  
  5. }  


Adapter role:

  1. public class ClassAdapter extends Adaptee implements Target {  
  2.       
  3.     public void request() {  
  4.         this.specificRequest();  
  5.     }  
  6. }  


User role:

  1. public class TestClassAdapter {  
  2.     public static void main(String args[]){  
  3.         ClassAdapter adapter =  new  ClassAdapter();  
  4.         adapter.request();  
  5.     }  
  6. }  

 

3. Illustration example 2: b. Adapter mode instance code of the object:  target role, the source role code remains unchanged. Adapter role: 



  1. public class ObjectAdapter implements Target {  
  2.       
  3.     private Adaptee adaptee;  
  4.       
  5.     public ObjectAdapter(Adaptee adaptee){  
  6.         this.adaptee = adaptee;  
  7.     }  
  8.     public void request() {  
  9.         adaptee.specificRequest();  
  10.     }  
  11.   
  12. }  


User role:

  1. public class TestOjbectAdapter {  
  2.     public static void main(String arg[]){  
  3.         Adaptee adaptee = new Adaptee();  
  4.         ObjectAdapter adapter = new ObjectAdapter(adaptee);  
  5.         adapter.request();  
  6.     }  
  7. }  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326313020&siteId=291194637