Design Mode learning notes-Adapter Mode

Source: Internet
Author: User


Before model learning


What is the design model: when we design the program, we gradually formed some typical problems and solutions, which is the software model; each mode describes a problem that often occurs in our program design and the solution to the problem. When we encounter the problem described by the mode, the corresponding solution can be used to solve the problem. This is the design mode.

A design pattern is an abstract thing. It is not learned but used. Maybe you don't know any pattern at all, and you don't consider any pattern, but write the best code, even from the perspective of "pattern experts", they are all the best designs and have to say "best pattern practices". This is because you have accumulated a lot of practical experience, knowing "where to write code" is a design pattern.

Some people say: "If the level is not reached, you can learn it in vain. If the level is reached, you can do it yourself ". It is true that the mode is well-developed and may still not be able to write good code, let alone design a good framework. OOP understanding and practical experience reach a certain level, and it also means to summarize a lot of good design experience, however, it may not be the case that "no teacher can do anything", or you can say that, on the basis of level and experience, it is time for the system to learn the "mode, it is helpful to learn the experts' summary and verify your own shortcomings.

This series of design patterns learning notes is actually a Learning Record for the book "Java and patterns.


Adapter mode definition


In the adapter mode, the interface (source) of a class is transformed into another interface (destination) expected by the client ), so that the two classes that cannot work together due to interface mismatch can work together.

Name:

Just like a transformer, a voltage is transformed into another voltage. 110 V of domestic electricity in the United States, 220 V of China, and American electrical appliances in China must have a transformer capable of converting the 220 V voltage into the 110 V voltage. This is like what the current model does, so this mode is often called the transformer mode.

The following two modes are available:

The adapter mode has two different forms: "class adapter mode" and "Object Adapter mode.


Class adapter Mode


In this way, the Adapter and the source are inherited relationships.


The role involved in the mode is:

(1) Target role: This is the expected interface. Note that because the class adapter mode is discussed here, the target cannot be a class.

(2) Source (Adaptee) role: the existing interface to be adapted.

(3) Adapter role: the Adapter class is the core of this mode. The adapter converts the source interface to the target interface. Obviously, this role cannot be an interface, but must be a specific class.

Code implementation:

Interface Target {void sampleOp1 (); // The Source class has this method void sampleOp2 ();} class Adaptee {public void sampleOp1 (){};} class Adapter extends Adaptee implements Target {public void sampleOp2 () {}; // This method is added to the Adapter class because the source class does not have this method}

Object Adapter Mode


In this way, the Adapter and the source (Adaptee) are delegate relationships. The "Adapter" delegates the "Source" and can pass the "Source" into the Adapter through the constructor or set method.


The role involved in the mode is:

(1) Target role: This is the expected interface. The target can also be a specific or abstract class.

(2) Source (Adaptee) role: the existing interface to be adapted.

(3) Adapter role: the Adapter class is the core of this mode. The adapter converts the source interface to the target interface. Obviously, this role cannot be an interface, but must be a specific class.

Code implementation:

Interface Target {void sampleOp1 (); // The Source class has this method void sampleOp2 ();} class Adaptee {public void sampleOp1 (){};} class Adapter implements Target {private Adaptee adaptee; public Adapter (Adaptee adaptee) {super (); this. adaptee = adaptee;} // This method is available in the source class. Directly delegate public void sampleOp1 () {adaptee. sampleOp1 () ;}public void sampleOp2 () {}; // This method is added to the adapter class because the source class does not have this method}

Under what circumstances do I use the adapter mode?


(1) The system needs to use existing classes, and such interfaces do not meet the requirements of the system.

(2) create a reusable class for some classes that are not highly correlated with each other, including some classes that may be introduced in the future. These source classes do not necessarily have very complex interfaces.

(3) In the design, if you need to change the interfaces of multiple existing sub-classes, for the "class adapter mode", you need to do multiple adapter classes to inherit the sub-classes separately. This is not practical, "Object Adapter mode" is often used ".


JDK1.2 has no Iterator (set Iterator) and only Enumeration. The following Code demonstrates an example and provides an "from Enumeration to Iterator" adapter.

import java.util.*;public class Enumeration2Iterator implements Iterator{Enumeration enu;public Enumeration2Iterator(Enumeration enu){this.enu = enu;}public boolean hasNext(){return enu.hasMoreElements();}public Object next(){return enu.nextElement();}public void remove(){throw new UnsupportedOperationException();}}

Default Adapter Mode


(1) The Adapter mode also has a special case called "Default Adapter mode". "Default Adapter mode" provides Default implementation for an interface, here, the child type can be extended from this default implementation, rather than from the original interface. The default adaptation mode is a mediocre adapter mode that provides a "mediocre" implementation or empty implementation for the target interface.

(2) The center of the default adaptation mode is a default adaptation class. This class should be an abstract class because it should not be instantiated and Its instantiation is useless.

(3) but the method provided by the default adaptation class should be a specific method, rather than an abstract method, because according to the intention of the pattern, these methods exist to provide the default implementation, so that the specific subclass of the default adaptive class can only implement the method as needed, ignoring the methods that do not need to be implemented.

Code Demonstration:

Interface monk {void eat Zhai (); void read Sutra (); void Xi Wu () ;}// this abstract day Lone Star is an adapter class, lu zhishen implements the monk interface by means of the "adapter mode" to achieve shaving. abstract class day Lone Star implements monk {public void vegetarian () {} public void chanting () {} public void Xi Wu () {}} class Lu zhishen extends day Lone Star {public void Xi Wu () {// do something }}

Learn more


(1) The following Code shows that CollectionData is also an instance of the adapter design mode. It adapts the Generator to the constructor of CollectionData. Bruce Eckel, author of Java programming ideas, believes that this may not be a strict definition of the adapter, But it conforms to the basic spirit of the adapter idea.

(2) The Code is as follows:

Import java. util. *; // Generator is a tool class used to instantiate the interface Generator of an object.
 
  
{T next ();} class BasicGenerator
  
   
Implements Generator
   
    
{Private Class
    
     
Type; public BasicGenerator (Class
     
      
Type) {this. type = type;} public T next () {try {return type. newInstance () ;}catch (Exception e) {throw new RuntimeException (e) ;}} public static
      
        Generator
       
         Create (Class
        
          Type) {return new BasicGenerator
         
           (Type) ;}}// CollectionData is an adapter class used to adapt Generator to CollectionData class CollectionData
          
            Extends ArrayList
           
             {Public CollectionData (Generator
            
              Gen, int quality) {for (int I = 0; I
             
               CollectionData
              
                List (Generator
               
                 Gen, int quality) {return new CollectionData
                
                  (Gen, quality );}}
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
 


Related Article

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.