代码之家  ›  专栏  ›  技术社区  ›  M. Pilarczyk

如何确保合成方法的安全?

  •  1
  • M. Pilarczyk  · 技术社区  · 8 年前

    我有 PC 类别和 Monitor 班 如何确保类监视器的方法在电脑关闭时无法使用(状态)?

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

    和内部 班长

    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() 收益 Object ,所以我不能试着抓住它。

    有人能帮我怎么处理吗?

    3 回复  |  直到 8 年前
        1
  •  1
  •   Nicolas Filotto    8 年前

    假设 Monitor 只能通过访问 getTheMonitor() 来自你的班级 PC ,你可以把你的 班长 实例导入装饰器,该装饰器将检查 status true 如果没有,它可能会抛出异常或忽略调用。

    这个 加入你的课堂 Pc :

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

    那么你的方法 获取监视器() 将是:

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

    这假设您在 MonitorStatusAware 班长 其中你有方法 drawPixelArt ,在这个例子中,我假设 班长 是您的界面。

        2
  •  0
  •   Jorge_B    8 年前

    我认为您已经将PC对象设计为其各个部分的集合,并使用它们之间的组合关系。然而,这里的弱点是允许访问实际组件,因为这可能会违反您自己放置的不变量(例如,除非电脑已打开,否则您无法在显示器中绘制,这非常合理)。

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

        3
  •  0
  •   Friddl    8 年前

    如果您绑定到这个设计,您可以检查监视器的getter中的状态,并抛出一个IllegalStateException。