Chi*_*ang 4 java design-patterns
以下Java设计允许在不更改其与客户端的接口的情况下扩展对象.该对象可以实现其他扩展接口.客户端可以向对象询问它实现的扩展接口.我在一篇博客文章中看过它,但我的谷歌技能再次找不到博客文章.我不是在提倡这种设计的优点.我只是想找到这篇博文.
例如,想象一下运输车辆的领域模型.每个车辆对象实现此接口:
public interface Extendable {
/**
* Asks the object if it provides the extension.
*
* @param extensionInterface
* requested extension
* @return object implementing the requested extension, or {@code null} if
* not available.
*/
<T> T queryExtension(Class<T> extensionInterface);
}
Run Code Online (Sandbox Code Playgroud)
固定翼飞机具有飞行控制面,但其他类型的车辆没有.为控制界面功能定义界面:
public interface ControlSurfaces {
String getAilerons();
String getElevator();
String getRudder();
}
Run Code Online (Sandbox Code Playgroud)
固定翼飞机类提供ControlSurfaces扩展:
public class FixedWingAircraft extends Vehicle {
@SuppressWarnings("unchecked")
public <T> T queryExtension(Class<T> extensionInterface) {
if (ControlSurfaces.class.equals(extensionInterface)) {
return (T) new ControlSurfacesImpl();
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
假设域模型是贫血域模型,因此服务对象负责将车辆对象保存到持久存储.该服务必须向车辆询问必须保存的扩展接口.
public class VehicleServiceImpl {
private VehicleDao vehicleDao;
private ControlSurfacesDao controlSurfacesDao;
public void save(Vehicle vehicle) {
vehicleDao.save(vehicle);
ControlSurfaces controlSurfaces = vehicle.queryExtension(ControlSurfaces.class);
if (controlSurfaces != null) {
controlSurfacesDao.save(vehicle, controlSurfaces);
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
这是"扩展接口"模式的Java实例,如"Pattern-Oriented Software Architecture"Vol.2(POSA-2),作者:Schmidt,Stal,Rohnert和Buschmann,Wiley,2000.
| 归档时间: |
|
| 查看次数: |
1495 次 |
| 最近记录: |