<分区>
我使用 Java 并尝试在不同的情况下为不同的事物分配不同的任务,但有时它们会做同样的事情。这会导致一些重复(实际上是长行,而不是短方法名称),但是有没有一种简单的方法可以避免这些重复?
if(direction == Direction.UP) {
doThingA(); // same thing as down
doCustomThing1();
doSameThing(); // all do this
doCustomThing5();
} else if(direction == Direction.DOWN) {
doThingA();
doCustomThing2();
doSameThing();
doCustomThing6();
} else if(direction == Direction.RIGHT) {
doThingB() // same thing as left
doCustomThing3();
doSameThing();
doCustomThing7();
} else if(direction == Direction.LEFT) {
doThingB()
doCustomThing4();
doSameThing();
doCustomThing8();
}
这是真正的代码,正如您所看到的,自定义的东西只是略有不同,但我不知道如何简化它:
if(direction == Direction.UP) {
box.setAsBox(size.value/2, Constants.WORLD_HEIGHT/2);
bodyDef.position.set(new Vector2(rand.nextFloat()*(Constants.WORLD_WIDTH-size.value)+size.value/2, -Constants.WORLD_HEIGHT*0.5f));
body = gameWorld.world.createBody(bodyDef);
body.setLinearVelocity(new Vector2(0f, 5f));
} else if(direction == Direction.DOWN) {
box.setAsBox(size.value/2, Constants.WORLD_HEIGHT/2);
bodyDef.position.set(new Vector2(rand.nextFloat()*(Constants.WORLD_WIDTH-size.value)+size.value/2, Constants.WORLD_HEIGHT*1.5f));
body = gameWorld.world.createBody(bodyDef);
body.setLinearVelocity(new Vector2(0f, -5f));
} else if(direction == Direction.RIGHT) {
box.setAsBox(Constants.WORLD_WIDTH/2, size.value/2);
bodyDef.position.set(new Vector2(-Constants.WORLD_WIDTH*0.5f, rand.nextFloat()*(Constants.WORLD_HEIGHT-size.value)+size.value/2));
body = gameWorld.world.createBody(bodyDef);
body.setLinearVelocity(new Vector2(5f, 0f));
} else if(direction == Direction.LEFT) {
box.setAsBox(Constants.WORLD_WIDTH/2, size.value/2);
bodyDef.position.set(new Vector2(Constants.WORLD_WIDTH*1.5f, rand.nextFloat()*(Constants.WORLD_HEIGHT-size.value)+size.value/2));
body = gameWorld.world.createBody(bodyDef);
body.setLinearVelocity(new Vector2(-5f, 0f));
}