如何确保组合方法?

How to secure methods of composition?

我有 PC class 和 Monitor class。 如何确保 class 显示器在 PC 关闭(状态)时无法使用?

public class Pc {
private Case theCase;
private Monitor theMonitor;
private Motherboard theMotherboard;
private boolean status;

public void turnOn(){
    System.out.println("Pc turned on!");
    status = true;
}
public void turnOff(){
    System.out.println("Pc turned off!");
    status = false;
}

Monitorclass

里面
public void drawPixelArt(int heigh, int width, String color){
    System.out.println("Drawing pixel at " + heigh + " x "+ width + " px.");
}

所以当(status == false)我不想调用任何方法。

例如thePc.getTheMonitor().drawPixelArt(1200, 1000, "RED");

getTheMonitor() returns Object,所以我没法抓到它

谁能帮我解决一下?

如果您受限于此设计,您可以检查监视器 getter 中的状态并抛出 IllegalStateException 左右。

假设 Monitor 只能通过 getTheMonitor() 从您的 class PC 访问,您可以将 Monitor 实例包装到装饰器中将检查 status 是否为 true,如果不是,它会抛出异常或忽略调用。

内class放入你的classPc:

private class MonitorStatusAware implements Monitor {
    public void drawPixelArt(int heigh, int width, String color){
        if (status) {
            theMonitor.drawPixelArt(heigh, width, color)
        } else {
            throw new IllegalStateException("The pc is switched off")
        }
    }
}

那么您的方法 getTheMonitor() 将是:

public Monitor getMonitor() {
    return new MonitorStatusAware();
}

这假设您在 MonitorStatusAwareMonitor 之间有一个共同的接口,其中您有方法 drawPixelArt,在这个例子中我假设 Monitor 是你的界面。

我认为您已经将 PC 对象适当地设计为其部分的集合,利用它们之间的组合关系。然而,这里的弱点是提供对实际组件的访问权限,因为它可能会违反您自己放置的不变量(例如,除非 PC 已打开,否则您无法在监视器中绘制,这是非常合理的)。

也许您想隐藏组件的细节并通过 PC 对象为每个操作提供统一的接口,以某种方式实现 Facade 模式(https://en.wikipedia.org/wiki/Facade_pattern)