Adapter mode: The interface of one class becomes the other interface that the client expects, so that the two classes that cannot work together because the interface does not match can work together.
The adapter has two forms: the adapter for the class and the adapter for the object.
class's Adapter mode
Structure diagram:
As you can see, adaptee is not operateb, and the client expects this method. In order for the client to use the Adaptee class, an intermediate link is added, namely the class adapter, which connects Adaptee API with the target class API. Adapter and adaptee are inheritance relationships, which determines that the adapter pattern is class.
Role:
target role : the desired interface--target
Source Role : The interface to be adapted now--adaptee
Adapter Role : Adapter converts the source interface into a target interface
Package Com.design.adapter.classadapter; Public Interface Target { void Operatea (); void operateb ();}
Adaptee
Package Com.design.adapter.classadapter; Public class adaptee { publicvoid Operatea () { }}
Adapter
Package Com.design.adapter.classadapter; Public class extends Implements Target { @Override publicvoid operateb () { }}
The adapter mode of the object
Structure diagram:
Unlike the class's adapter pattern, an object's adapter mode is not connected to the Adaptee class using an inheritance relationship, but instead uses a delegation relationship to connect to the Adaptee class.
There is no Operateb method in Adaptee, and the client expects this method. For the client to be able to use the Adaptee class, an adapter class is required. This adapter class wraps a Adaptee instance so that the Adaptee API can be connected to the target API. The Adaptee and Adapter classes are for delegation relationships, which determines that this adapter pattern is an object.
Target
Package Com.design.adapter.objectadapter; Public Interface Target { void Operatea (); void operateb ();}
Adaptee
Package Com.design.adapter.objectadapter; Public class adaptee { publicvoid Operatea () { }}
Adapter
PackageCom.design.adapter.objectadapter; Public classAdapterImplementsTarget {Privateadaptee adaptee; PublicAdapter (adaptee adaptee) { This. Adaptee =adaptee; } /*** The source class has a method, so the direct delegation can*/@Override Public voidOperatea () {Adaptee.operatea (); } /*** The source class does not have this method and requires an adapter implementation*/@Override Public voidOperateb () {}}
Description
The adapter mode is intended to convert two interfaces with different interfaces and functions, including the adapter role, which complements the method of a source role. Do not mistakenly assume that the adapter pattern is intended to complement the methods that the source role does not have.
Java design mode--Adapter mode