需要引用Java中的扩展接口模式

时间:2009-06-28 21:29:48

标签: 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);
}

固定翼飞机具有飞行控制面,但其他类型的车辆没有。为控制界面功能定义界面:

public interface ControlSurfaces {
    String getAilerons();
    String getElevator();
    String getRudder();
}

固定翼飞机类提供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;
    }
}

假设域模型是anemic domain model,因此服务对象负责将车辆对象保存到持久存储。该服务必须向车辆询问必须保存的扩展接口。

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);
        }
    }
}

2 个答案:

答案 0 :(得分:5)

这是“扩展接口”模式的Java实例,如“Pattern-Oriented Software Architecture”Vol。 2(POSA-2),作者:Schmidt,Stal,Rohnert和Buschmann,Wiley,2000。

答案 1 :(得分:0)

你的意思是using proxies to expose an interface at runtime吗?对不起,但你的问题很混乱。我不知道如何培养贫血领域模式有助于解决问题。