我有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();
}
这假设您在 MonitorStatusAware
和 Monitor
之间有一个共同的接口(interface),其中您有方法 drawPixelArt
,在本例中我假设Monitor
是您的界面。
关于java - 如何确保组合方法的安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39180619/