The Adapter Pattern of Java Design Patterns

adapter mode

  • As a bridge between two incompatible interfaces.
  • structural pattern

1. Class Adapter Pattern

The method to be accessed is not in the appropriate interface

The Adapter class implements the dst class interface by inheriting the src class to complete the adaptation of src->dst

//适配器模式 继承目的类  实现源接口
//Rest --> Work
class AdapterRest extends WorkA implements Rest {
    public void doRest() {
        doWork();
    }
}

advantage:

  • Overridable methods of the src class

shortcoming:

  • All class adapters need to inherit from the src class
  • Requires that dst must be an interface

2. Object Adapter Pattern

Holds the src class, implements the dst class interface, and completes the adaptation of src->dst

//对象适配器
class AdapterRest implements Rest{
    private Work work;
    public AdapterRest(Work work){
        this.work = work;
    }
    public void doRest() {
        work.doWork();
    }
}

test:

AdapterRest adapter = new AdapterRest(new WorkA());
adapter.doRest();//do work A

3. Interface adapter

want to use a method or methods in the interface

You can use an abstract class to implement the interface without implementing the method.
Then we inherit this abstract class to implement it by overriding the required methods.

This abstract class is the adapter.

abstract class Adapter implements Rest{}
class AdapterRest extends Adapter{
    public void doRest() {
        System.out.println("do rest by adapterRest");
    }
}

Guess you like

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