In computer programming, the adapter mode (sometimes called packaging style or packaging) adapts an interface of a class to what the user expects. An adaptation allows classes that are usually unable to work together because of incompatibility of interfaces, by wrapping the class's own interface in an existing class.
Features: Two incompatible classes are implemented together through interfaces
Applications in enterprise-level development and common frameworks: stream interfaces, such as converting character streams into byte stream outputs, are used to use outputstreamreader
Adapter mode is divided into class adapter and object adapter:
For example: the computer only has a USB interface, but the keyboard only has a round port. At this time, an adapter is needed to enable the keyboard to enter data to the computer.
Class Adapter:
package com.test.adapter;public class Computer { public void show(USB usb){ usb.recive(); System.out.println("Computer displays input data"); } public static void main(String[] args) { Computer c = new Computer(); USB u = new USBAdapter(); c.show(u); }}class KeyBoard{ public void input(){ System.out.println("Keyboard input data"); }}/** * Adapter interface*/interface USB{ public void recive();}/** * Specific adapter*/class USBAdapter extends KeyBoard implements USB{ public void recive() { System.out.println("I am a USB adapter, I enable the round-port keyboard to connect to the USB interface computer"); super.input(); } }Object Adapter:
package com.test.adapter;public class Computer { public void show(USB usb){ usb.recive(); System.out.println("Computer displays input data"); } public static void main(String[] args) { Computer c = new Computer(); KeyBoard k = new KeyBoard(); USB u = new USBAdapter(k); c.show(u); }}class KeyBoard{ public void input(){ System.out.println("Keyboard input data"); }}/** * Adapter interface*/interface USB{ public void recive();}/** * Specific adapters*/class USBAdapter implements USB{ private KeyBoard k; public USBAdapter(KeyBoard k) { this.k = k; } public void recive() { System.out.println("I am a USB adapter, I enable the round-port keyboard to connect to the USB interface computer"); k.input(); } }Relatively speaking, object adapters are more flexible in combination than class adapters through integration. It is recommended to use object adapters in daily life.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.