java - 如何确保组合方法的安全?

标签 java methods composition

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

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

以及Monitor类内部

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,因此我无法 try catch 它。

有人可以帮我解决这个问题吗?

最佳答案

假设 Monitor 只能通过 getTheMonitor() 从您的类 PC 访问,您可以包装您的 Monitor 实例放入一个装饰器中,该装饰器将检查 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")
        }
    }
}

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

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

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

关于java - 如何确保组合方法的安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39180619/

相关文章:

java - 如何在 ListView 中获取所选项目的值 - Android

java - 刷新输入流 : java

java - 如何在公共(public)方法中创建私有(private)变量

python - 为什么 python 中的函数/方法需要 self 作为参数?

android - 从 fragment 调用 Activity 方法

scala - 通过在Scala中组合Option [predicate]函数来构建最小谓词功能(可能与scalaz一起使用)

Perl 类的属性组成?

mvvm - 在 MVVM 应用程序中为 MEF 使用组合模型是否有好处?

java - 在运行时检索 log4j2 配置属性(如果已定义)

java - Android 后退按钮 react 太快