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 的新实例,并且不会达到目的。
添加回答
举报