/**
* 适配器:电能适配器
*/
public class ElectricAdapter implements Motor {
private final ElectricMotor electric;
public ElectricAdapter() {
this.electric = new ElectricMotor();
}
@Override
public void drive() {
electric.electricDrive();
}
}
ElectricMotor.java
/**
* 适配者:电能发动机
*/
public class ElectricMotor {
public void electricDrive(){
System.out.println("我是电能发动机,正在发动。。。");
}
}
Motor.java
/**
* 目标接口:发动机
*/
public interface Motor {
void drive();
}
OpticalAdapter.java
/**
* 适配器:光能适配器
*/
public class OpticalAdapter implements Motor {
private final OpticalMotor optical;
public OpticalAdapter() {
this.optical = new OpticalMotor();
}
@Override
public void drive() {
optical.opticalDrive();
}
}
OpticalMotor.java
/**
* 适配者:光能发动机
*/
public class OpticalMotor {
public void opticalDrive(){
System.out.println("我是光能发动机,正在发动。。。");
}
}
双向适配
结构图
AdapteeRealize.java
/**
* 适配者实现类:
*/
public class AdapteeRealize implements TwoWayAdaptee {
@Override
public void specificRequest() {
System.out.println("适配者代码被调用!");
}
}
TargetRealize.java
/**
* 目标实现:实现接口
*/
public class TargetRealize implements TwoWayTarget {
@Override
public void request() {
System.out.println("目标代码被调用!");
}
}