技术开发 频道

用AspectJ增强设计模式上

    Java 语言的适配器

    适配器模式的传统实现方式是:用一个实现了方便的 API 的类来包装每个目标。在这种情况下,要创建一个公共接口,比如 StatusSensor,如下所示:
public interface StatusSensor { String getStatus(); }

    有这个公共接口存在,就可以像以下这样实现读取器方法:

for (StatusSensor sensor : allSensors) { System.out.print("Sensor " + count++); System.out.println(" status is " + sensor.getStatus()); }

    剩下的惟一挑战就是让每个传感器符合这个接口。适配器类可以实现这一点。在清单 1 中可以看到,每个适配器都以成员变量的形式保存自己包装的传感器,用这个底层的传感器实现 getStatus 方法:

    清单 1. 适配器类和客户代码

//Adapter classes public class RadiationAdapter implements StatusSensor { private final RadiationDetector underlying; public RadiationAdapter(RadiationDetector radiationDetector) { this.underlying = radiationDetector; } public String getStatus() { if(underlying.getCurrentRadiationLevel() > 1.5){ return "DANGER"; } return "OK"; } } public class TemperatureAdapter implements StatusSensor { //...similar } //glue code to wrap each sensor with its adapter... allSensors.add(new RadiationAdapter(radiationDetector)); allSensors.add(new TemperatureAdapter(gauge));

    清单还显示了在读取器之前用适当的适配器包装每个传感器的“胶水代码”。模式并没有指定这个胶水代码应当在哪个具体位置出现。可能的位置包括“创建之后”和“使用之前”。可以将示例代码放在向读取器集合添加传感器之前。

0
相关文章