以这种方式使用类的字段和方法是否正确: -
//Class A
class Main
{
//Fields that are also needed by the "Player" object
String[] moveArray;
int screenWidth;
int screenHeight;
int leftLimit;
int rightLimit;
int upLimit;
int downLimit;
boolean left;
boolean right;
boolean up;
boolean down;
//and more
private Player player=new Player();;
public void run()
{
//Pass this object's reference to the "Player" object, before entering the infinite loop
player.main=this;
while(isRunning)
{
update();
repaint();
}
}
}
//Class B
class Player
{
//stores "Main" object's reference
Main main;
float playerX;
float playerY;
//Accessing the fields that are inside the "Main" object, using its reference
private void moveLR()
{
if(main.left)
{
playerX-=0.5f;
}
else if(main.right)
{
playerX+=0.5f;
}
}
private void moveUD()
{
if(main.up)
{
playerY-=0.5f;
}
else if(main.down)
{
playerY+=0.5f;
}
}
public void update(){
if(playerX > main.leftLimit && playerX < main.rightLimit)
{
moveLR();
}
if(playerX > main.upLimit && playerX < main.downLimit)
{
moveUD();
}
}
}
如果我使用它们,将会有太多的getter和setter,因为该项目将包含许多类,每个类包含许多需要使用其他对象的方法。成员。以上过程是正确的,还是将字段声明为私有并使用getter / setter以最佳方式访问所有字段?谢谢!
答案 0 :(得分:3)
您是否知道名为Feature envy的代码气味?
通常,您希望访问很多邻居的字段,而不会意识到这些字段最适合/移动到使用它们最多的类。
此外,OOP本质上是“向邻居传递信息”
尽可能避免使用getter / setter (通常=> 95%的用例)并遵循Tell! Don't Ask!理念。
我们的想法是告诉邻居行为,而不是询问数据。
=&GT;这是与C等程序语言的最大区别。
IMO,Player
应tryToMoveTo
,如果成功,update
应出现area
:
public void tryToMoveTo(direction Direction) {
if(this.canMoveTo(direction))
area.update(direction); //I tell to update, not ask for coordinates that would make the player responsible for data that doesn't concern it at all.
else
throw new InvalidPlayerMove();
}
避免所有丑陋的getter和setter。
答案 1 :(得分:0)
使用getter和setter。当您决定添加更多逻辑时,它将为您节省许多麻烦。