我尝试将主对象中的对象更改为另一种类型的对象。这是一些代码,可以了解我的实际意思。
Main.java
public class Main {
public static void main(String[] args) {
Controller newcontroller = Controller.create();
newcontroller.change();
}
}
Controller .java:
public class Controller{
public static Controller create() {
return new North(0,0);
}
public void change() {
}
}
北.java:
public class North extends Controller{
int x;
int y;
public North(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public void change() {
super.change();
//Now i have to replace the newcontroller North(x,y) by South(x,y)
super.newcontroller = new South(this.x, this.y)
}
}
South.java 和 North 一样,但又变成了 North。 我怎样才能做到这一点?或者我完全以错误的方式做这件事? 不允许使用 if, switch, for, while, ... 只能使用线性编程
最佳答案
执行此操作的一个简单方法是在 Controller 类中添加一个 boolean 标志并检查该标志是否发生更改,但不应这样做,因为它不遵循 OOP 原则。在上面的代码中,您似乎正在创建一个返回 Controller 的工厂。
public class ControllerFactory {
public static CreateController(boolean isNorth) {
return isNorth ? new North() : new South();
}
}
无论您在何处实例化 Controller ,都有一个 boolean 值来保存 Controller 的当前状态。
boolean isNorth = true;
isNorth = !isNorth;
controller = ControllerFactory.CreateController(isNorth);
关于java - 在 Main[JAVA] 中用另一种类型的对象替换对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62108200/