我有 - Worker 界面。 每个 worker 都有能量。
public interface Worker {
int work();
double getEnergy();
}
和 - JuniorWorker 类,实现 Worker 接口(interface)。 初级 worker 有100能量。
public class juniorWorker implements Worker {
public int work() {
return (int) getEnergy();
}
public double getEnergy() {
return 100;
}
}
并且还有 - effectiveWork、powerWork 类,实现 Worker 接口(interface)。 高效工作将减少20%的能源。 powerWork 将使能量提高 10%。
public class efficientWork implements Worker {
private Worker worker;
public efficientWork(Worker w) {
this.worker=w;
}
public int work() {
return (int) (worker.getEnergy()*getEnergy());
}
public double getEnergy() {
return 0.8;
}
}
public class PowerWork implements Worker {
private Worker worker;
public PowerWork(Worker w) {
this.worker=w;
}
public int work() {
return (int) (worker.getEnergy()*getEnergy());
}
public double getEnergy() {
return 1.1;
}
}
实际上,我正在尝试 int work() 来总结每个 worker 将花费的总能量。 例如我的Demo类:
public class Demo {
public static void main(String[] args) {
Worker j= new efficientWork(new juniorWorker());
System.out.println(j.work());
}
}
此案例正在运行 - 系统将打印80。
但是这个例子,总是打印 0 :
public class Demo {
public static void main(String[] args) {
Worker j= new efficientWork(new PowerWork(new juniorWorker()));
System.out.println(j.work());
}
}
帮忙?我期待得到88! (110*0.8)
最佳答案
您应该调用 work()
不是getEnergy()
方法在装饰器内保存的封闭工作对象上 work()
方法。
// decorator's work method
public int work() {
// return (int) (worker.getEnergy() * getEnergy()); // NO!
return (int) (worker.work() * getEnergy()); // YES!
}
关于java - JAVA中的装饰模式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41006076/