Table of contents
class adapter
Below we use a simple example of Mac computer and U disk adaptation to understand the implementation of class adapters.
First create a Mac interface with the function of reading and writing data
public interface MacInterface {
void write(String msg);
String read();
}
Then there is an instance of a u disk
public class UDisk {
public void byWrite(String msg){
System.out.println(msg);
}
public String byRead(){
return "拜登家谱";
}
}
But the mac interface is directly connected to the u disk, so we add an adapter to it and connect the two through the adapter.
public class MacUsbAdaptor extends UDisk implements MacInterface{
@Override
public void write(String msg) {
super.byWrite(msg);
}
@Override
public String read() {
return super.byRead();
}
}
public class AdaptorTest {
@Test
public void test(){
MacInterface macInterface = new MacUsbAdaptor();
System.out.println(macInterface.read());
macInterface.write("川普私密照片");
}
}
=====结果=====
拜登家谱
川普私密照片
object adapter
Using the same example as above, the object adapter is implemented by composition.
public interface MacInterface {
void write(String msg);
String read();
}
public class UDisk {
public void byWrite(String msg){
System.out.println(msg);
}
public String byRead(){
return "拜登家谱";
}
}
public class MacUsbAdaptor implements MacInterface {
private UDisk disk;
public MacUsbAdaptor(UDisk disk) {
this.disk = disk;
}
@Override
public void write(String msg) {
//适配过程中肯定涉及到一些 “适配” 的过程,比如说统一格式
disk.byWrite(msg);
}
@Override
public String read() {
return disk.byRead();
}
}
public class AdaptorTest {
@Test
public void test(){
MacInterface macInterface = new MacUsbAdaptor(new UDisk());
System.out.println(macInterface.read());
macInterface.write("川普私密照片");
}
}
=====结果=====
拜登家谱
川普私密照片
Choice of two adapters
- There are not many interfaces (methods in the class) of the adapted class (such as UDisk), both can be
- If the class to be adapted has many interfaces and most of the interfaces need to be adapted to the methods in the interface class (such as MacInterface), you can choose a class adapter, which can reuse the methods in the adapted class and save the amount of code.
- If the class to be adapted has many interfaces and its interface and the methods in the interface class (such as MacInterface) are not adapted much, you can choose an object adapter, and composition is more flexible than inheritance.
scenes to be used
- The original interface cannot be modified but must be quickly compatible with the new interface
- Conversion between different data formats and protocols
- Need to use external components to combine into new components to provide functionality without duplicating some functionality
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。