我尝试将对象更改为我主体中的另一种类型的对象。这是一些代码,以了解我的实际意思。
Main.java
public class Main {
public static void main(String[] args) {
Controller newcontroller = Controller.create();
newcontroller.change();
}
}
Controler.java:
public class Controller{
public static Controller create() {
return new North(0,0);
}
public void change() {
}
}
North.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就像北方的,但是再次变为北方。我怎样才能做到这一点?还是我以一种错误的方式完全完成了它?它不允许使用if,switch,for,while,...仅线性编程
一种简单的方法是在Controller类中具有一个布尔标志,并检查该标志是否更改,但是不应这样做,因为它不遵循OOP原则。在上面的代码中,您似乎正在创建一个返回控制器的Factory。
public class ControllerFactory {
public static CreateController(boolean isNorth) {
return isNorth ? new North() : new South();
}
}
以及在实例化Controller的任何地方都有一个布尔值,用于保存控制器的当前状态。
boolean isNorth = true;
isNorth = !isNorth;
controller = ControllerFactory.CreateController(isNorth);
您需要一些修改。
public class Main {
public static void main(String[] args) {
Controller ctl = Controller.create();
ctl.change();
}
}
public class Controller{
public static Controller create() {
return new North(0,0);
}
public Controller change() {
return null;
}
}
public class North extends Controller{
int x;
int y;
public North(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public Controller change() {
return new South(this.x, this.y);
}
}
public class South extends Controller {
int x;
int y;
public South(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public Controller change() {
return new North(this.x, this.y);
}
}