我想覆盖已经分配给变量的类的方法 例如:
inventory = new Inventory( );
/* Some code here that changes how inventory
must behave or whatever */
inventory
{
@Override ...
}
答案 0 :(得分:1)
也许您会想到这样的事情(而不是null - 如果您可以实现默认策略以使其更干净):
public interface Strategy {
public void doSomething();
}
public class Inventory {
Strategy strategy;
public Inventory() {
// ...
}
public void doSomething() {
if (strategy == null) {
System.out.println("strategy is empty");
} else {
strategy.doSomething();
}
}
public Strategy getStrategy() {
return strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
}
然后这个
Inventory inventory = new Inventory();
inventory.doSomething();
inventory.setStrategy(new Strategy() {
@Override
public void doSomething() {
System.out.println("strategy is now something different");
}
});
inventory.doSomething();
显示了这一点:
strategy is empty
strategy is now something different
有关更详细的版本,您可以查看strategy pattern。
答案 1 :(得分:1)
这里的作文肯定会有所帮助。而不是重写一个方法来改变Inventory
的行为,而不是传递方法:
class Inventory {
private MyMethod method;
public void setMethod(MyMethod method) {
this.method = method;
}
public void doSomething() {
method.doSomething();
}
}
interface MyMethod {
void doSomething();
}
您现在可以通过MyMethod
:
setMethod
的实施
Inventory inv = new Inventory();
//...
inv.setMethod(() -> {
//write method here
});
如果您不使用Java 8,则必须继承MyMethod
:
inv.setMethod(new MyMethod() {
public void doSomething() {
}
});