Design pattern twelve, adapter pattern

Adapter mode: The
adapter mode adapts the interface of a class to what the user expects. Adapter is a generally allows because of incompatible interfaces not work with the class to work together, to practice their class interfaces wrapped in an existing class into two forms of composition and inheritance

Inherited advantages :

A. Adapter can redefine part of the behavior of Adaptee.
B. No additional pointers are needed to get Adaptee indirectly.

Inherited disadvantages :

When you want to match another class and all its subclasses, the class Adapter will not be implemented.

Combination advantages :

One Adapter can work with multiple Adaptees and all its subclasses at the same time

Combination disadvantages :

Cannot redefine the behavior of Adaptee

适配器模式使用场景

A. Adapter mode is mainly used in situations where you want to reuse some existing classes, but the interface is inconsistent with the requirements of the reuse environment.
B. If you want to use an existing class, but if the interface of the class is not the same as the requirement, you should consider using the adapter mode.

//目标接口, 具有标准的接口
public interface Function {
    
    
    public void request();
}
    
//已经存在的, 并且具有特殊功能的类, 但是不符合我们既有的标准的接口的类
public class Adaptee {
    
    
    public void myrequest() {
    
    
        System.out.println("我的功能");
    }
}

//适配器, 直接关联被适配的类, 同时实现标准接口,组合方式
public class Adapter1 implements Function{
    
    
    Adaptee adaptee;

    public Adapter1(Adaptee adaptee) {
    
    
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
    
    
        System.out.println("进行适配1");
        adaptee.myrequest();
    }

}

//继承方式
public class Adapter2 extends Adaptee implements Function{
    
    

    @Override
    public void request() {
    
    
        System.out.println("进行适配2");
        super.myrequest();
    }

}

public class app {
    
    
    //服务请求者
    public static void setAdapter(Function function) {
    
    
        function.request();
    }

    public static void main(String[] args) {
    
    
        Adapter1 adapter1 = new Adapter1(new Adaptee());
        setAdapter(adapter1);

        Adapter2 adapter2 = new Adapter2();
        setAdapter(adapter2);
    }

}

Output

进行适配1
我的功能
进行适配2
我的功能

Guess you like

Origin blog.csdn.net/weixin_45401129/article/details/114629435