私は、不変クラスの概念についてはかなり新しいです。私は、このクラスは不変のものに変更することができる方法を理解しようとしていクラス内の不変性と状態の変化
public class ConnectionMonitor implements MessageConsumer {
private final MonitorObject monitorObject;
private boolean isConnected = true;
private final static Logger logger = LogManager.getLogger(ConnectionMonitor.class);
public ConnectionMonitor(final MonitorObject monitorObject) {
this.monitorObject = monitorObject;
}
public boolean isConnected() {
return isConnected;
}
public void waitForReconnect() {
logger.info("Waiting for connection to be reestablished...");
synchronized (monitorObject) {
enterWaitLoop();
}
}
private void enterWaitLoop() {
while (!isConnected()) {
try {
monitorObject.wait();
} catch (final InterruptedException e) {
logger.error("Exception occured while waiting for reconnect! Message: " + e.getMessage());
}
}
}
private void notifyOnConnect() {
synchronized (monitorObject) {
monitorObject.notifyAll();
}
}
@Override
public void onMessage(final IMessage message) {
if (message.getType() == IMessage.Type.CONNECTION_STATUS) {
final String content = message.getContent();
logger.info("CONNECTION_STATUS message received. Content: " + content);
processConnectionMessageContent(content);
}
}
private void processConnectionMessageContent(final String messageContent) {
if (messageContent.contains("Disconnected")) {
logger.warn("Disconnected message received!");
isConnected = false;
} else if (messageContent.contains("Connected")) {
logger.info("Connected message received.");
isConnected = true;
notifyOnConnect();
}
}
}
: このクラスを考えてみましょう。
特に、ブール値フィールドisConnected
が接続状態を表すため、最終的にどのように表示されるかわかりません。
ConnectionMonitor
のすべてのクライアントは、接続状態を取得するために isConnected()
を照会するだけです。
私は、isConnected
へのロック変更が可能であること、またはアトミックブール値を使用していることを認識しています。
しかし、これを不変クラスに書き換える方法はわかりません。
すべてのオブジェクトが不変である必要はありません。 –
私は、変更可能/不変のクラスをいつ作成するかを判断するだけの経験が必要ですか? – Juergen
体験が役に立ちます。一般的に、可能な場合は不変性を優先しますが、可能な場合に限ります。私は以下の答えで詳細を追加しました。 –