concept

The Adapter Pattern is a structural design Pattern that enables objects with incompatible interfaces to cooperate. The adapter pattern translates one interface into another that the customer wants, and the adapter pattern enables classes with incompatible interfaces to work together, alias Wrapper. The adapter pattern can be used as either a class schema or an object schema.

For example, you must have seen the funnel. When our vessel is small, we fill the vessel with liquid through the auxiliary tool, the funnel, which plays a suitable role.

Class adapters and object adapters

Adapters are divided into class adapters and object adapters

The class adapter

Use inherited adapters

The class diagram

/*** / public class Banner {public void showP(){//... } public void showA(){ //... }} public interface Print {// weaken void printable (); // reinforce void printStrong(); } public class BannerPrint extends Banner implements Print{public void printweaks () { super.showA(); } @override public void printStrong() {super.showp (); }}Copy the code

Object adapter

The principle of aggregation reuse is synthesized using a delegated adapter

The class diagram

// Object adapter: Based on the combination of public class Print {// weaken void printWeak(); // reinforce void printStrong(); } public class Banner { public void showP(){ //... } public void showA(){ //... } } public class BannerPrint extends Print { private Banner banner; public BannerPrint(Banner banner) { this.banner = banner; } // Override public void printweaks () {banner.showa (); } @override public void printStrong() {ban.showp (); }}Copy the code

The difference between

Implementation is different: class adapters are implemented using inheritance relationships, and object adapters are implemented using composition relationshipsCopy the code

His role

The target object

Use the Print interface when inheriting and the Print class when delegating to define the methods required by the roleCopy the code

Adapatee be adapted

Banner Is a component interface that is accessed and adapted from an existing component libraryCopy the code

Adapater adaptation

BannerPrint is a converter that converts the adapter interface into the target interface by inheriting or referencing the adapter's object, allowing the client to access the adapter in the format of the target interfaceCopy the code