我有PC
课程和Monitor
课程。
如何保护在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;
}
和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
,所以我无法抓住它。
有人可以帮我解决这个问题吗?
答案 0 :(得分:1)
假设只能通过您的班级Monitor
中的getTheMonitor()
访问PC
,您可以将Monitor
实例包装到装饰器中,以检查status
是否true
1}}是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
和drawPixelArt
之间有一个共同的接口,其中您使用方法Monitor
,在此示例中,我假设{
"username":"...",
"password":"...",
"identity_secret":"...",
"shared_secret":"...",
"hostname":"127.0.0.1",
"owner":"..."
}
是您的接口
答案 1 :(得分:0)
如果您受这个设计的约束,您可以检查监视器的getter中的状态并抛出IllegalStateException左右。
答案 2 :(得分:0)
我认为您已经使用它们之间的组合关系将PC对象正确设计为其各个部分的集合。但是,这里的弱点是允许访问实际组件,因为它可以违反您自己放置的不变量(例如,除非打开PC,否则无法在监视器中绘制,这非常有意义)。
也许你想要隐藏组件的细节,并通过PC对象为每个操作提供统一的界面,以某种方式实现Facade模式(https://en.wikipedia.org/wiki/Facade_pattern)