@Override
public void onMotionSensingEvent( MotionSensingEvent arg0) {
double gradient = 1.38;
double speed;
float testpitch = 0;
testpitch = arg0.getOrientation().getPitch();
float testroll = 0;
testroll = arg0.getOrientation().getRoll();
if (testroll > 16 && flyingControl)
{
speed = gradient*testroll-22.1;
System.out.println("kanan = " + speed);
ardrone.goRight(speed);
}
else if (testroll < (-24) && flyingControl)
{
speed = gradient*testroll*-1 - 22.1;
System.out.println("kiri = " + speed);
ardrone.goLeft(speed);
}
else if (testpitch < (-20) && flyingControl)
{
System.out.println("go up");
ardrone.up();
}
else if (testpitch > 20 && flyingControl)
{
System.out.println("go down");
ardrone.down();
}
}
@Override
public void onExpansionEvent(ExpansionEvent e)
{
JoystickEvent joy = getJoystickEvent(e);
float gradient =64;
float speed;
float angle = 0;
angle = joy.getAngle();
float magnitude = joy.getMagnitude();
if ((angle > 340 || angle < 20) && magnitude > 0.49 && flyingControl)
{
speed = gradient*magnitude-19;
ardrone.forward(speed);
}
else if ((angle > 160 && angle < 200) && magnitude > 0.49 && flyingControl)
{
speed = gradient*magnitude-19;
ardrone.backward(speed);
}
else if ((angle > 70 && angle < 110) && magnitude > 0.7 && flyingControl)
{
System.out.println("turn right ");
ardrone.spinRight();
}
else if ((angle > 250 && angle < 290) && magnitude > 0.7 && flyingControl)
{
System.out.println("turnleft ");
ardrone.spinLeft();
}
}
我有这段代码,我需要帮助将所有这些 IF-ELSE 内容从主类中删除,使其成为 OOP,但我不知道一个好的开始方法。我的主管说了一些关于听众的事情,但我听不懂。仅供引用,我有那些听众,但我没有将它们包括在这个问题中。
那么,有人能告诉我从主类中删除所有这些 IF ELSE 的步骤吗? 非常感谢!!
最佳答案
使用 chain of responsibility 怎么样? ?此处不同的行为可以封装在它们自己的类中。
在这种情况下,这些专门的类(class)将充当听众,正如您的老师所想的那样。
if/else block 中的每个语句序列都将封装在一个特定对象中。
这将极大地帮助我们继续遵循 Open/Closed Principle .
When more than one object may handle a request and the actual handler is not known in advance, you may use a Chain of Responsibility.
这里有一些与您类似的示例(来自 GUI 的事件):http://www.dcs.bbk.ac.uk/~oded/OODP13/Sessions/Session6/Chain.pdf
关于java - 如何将其变为 OOP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17231855/