1 回答

TA貢獻1836條經驗 獲得超4個贊
您可以按如下方式使用單例類(您可以將單例類重命名為您想要的任何其他名稱。)
public class SharedValues{
private static SharedValues sharedValues = new SharedValues();
//will always return the same instance of this class
public static SharedValues getInstance() {
return sharedValues;
}
private boolean capicua;
public void setCapicua(boolean capicua)
{
this.capicua = capicua;
}
public boolean getCapicua()
{
return this.capicua;
}
}
然后在 Servidor 類和 Client 類中,執行以下操作:
class Servidor {
SharedValues sharedValues = SharedValues.getInstance();
//make sure this while loop code is in a function
while(true)
{
if (numero == capicuar(numero)) {
sharedValues.setCapicua(false);
}
}
}
class Client {
SharedValues sharedValues = SharedValues.getInstance();
//make sure this while loop code is in a function
while(true)
{
boolean capicua = sharedValues.getCapicua();
System.out.println(capicua);
}
}
簡單解釋一下,單例類就是一個只能有一個實例的類。因此,SharedValues 類的同一個實例將被 Servidor 類和 Client 類訪問。如果您因此將 Servidor 中的值設置為setCapicua(false),那么在類 Client 中,如果您調用getCapicua() ,您將把它設置為 false 。但是,您必須意識到,在客戶端和服務器中,實例化是SharedValues sharedValues = SharedValues.getInstance();請不要使用SharedValues sharedValues = new SharedValues();這將提供類 SharedValues 的新實例,并且不會達到目的。
添加回答
舉報