JAVA design pattern-Adapter

Adapter

We learn a pattern, first understand it from the name. The common adapter in life is the power adapter. The function is to convert voltage and current into voltage and current required by electrical appliances.

We only need to remember one sentence, the adapter is to transform the class interface into another interface that the user needs ( conversion interface ).

In iphone11, iphone12 have different communication technologies. Now I want 11 to call the 5G signal interface, so I add an adapter to it.

public interface Iphone12 {
    
    
    void communicateBy5G();
}
public interface Iphone11 {
    
    
    void communicateBy4G();
}
public class Iphone11Impl implements Iphone11 {
    
    
    @Override
    public void communicateBy4G() {
    
    
        System.out.println("communicate by 4G!");
    }
}
public class Iphone11Adapter implements Iphone12 {
    
    
    Iphone11 iphone11;

    public Iphone11Adapter(Iphone11 iphone11) {
    
    
        this.iphone11 = iphone11;
    }

    @Override
    public void communicateBy5G() {
    
    
        iphone11.communicateBy4G();
    }
}
/**
** 可以看出虽然创建的对象是iphone12,但实际上使用的是4G通信。
**/
public class Client {
    
    
    public static void main(String[] args) {
    
    
        Iphone11 iphone11 = new Iphone11Impl();
        Iphone12 iphone12 = new Iphone11Adapter(iphone11);
        iphone12.communicateBy5G();
    }
}
//communicate by 4G!

Example

It can be seen that 4G is actually used, and the role of the adapter is that the person who uses it looks like it is using another class, but the actual operation is still the original object.

The following is the use of Arrays.asList() in the adapter mode. I believe that your understanding of the adapter will be better after reading it.

@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
    
    
    return new ArrayList<>(a);
}

Look again

ArrayList(E[] array) {
    
    
    a = Objects.requireNonNull(array);
}
  • It can be seen that the method knowledge of Arrays.asList(T... a) is not empty or not, and the address is assigned to a.
  • So, if you change the value of the list, the value of the original array will also change. The same goes for vice versa.

It can be seen that calling asList() returns List, but the actual storage structure is still an array. Here, the operation of operating the array is hidden, so that the user thinks that it is operating the List ( conversion interface ) that is the core idea of ​​the adapter.

Guess you like

Origin blog.csdn.net/weixin_43957211/article/details/111186037