Series: Angelia
java
70 lines
· Updated 2026-09-27
FakeChatClient.java
Angelia/Java/Week_6_7/code/08_chat_protocol/FakeChatClient.java
import java.util.ArrayList;
import java.util.List;
/**
* 「假的」客戶端:完全不碰網路,把所有訊息直接回送給監聽者。
*
* 用途:在伺服器還沒寫好之前,就能開發並「測試」UI——
* 這正是「對介面寫程式」帶來的好處:任何 ChatClient 的實作都可以互換。
*/
public class FakeChatClient implements ChatClient {
private final List<Listener> listeners = new ArrayList<>();
private boolean connected = false;
private String name;
private final List<String> rooms = new ArrayList<>();
@Override
public void addListener(Listener listener) {
this.listeners.add(listener);
}
@Override
public void connect(String host, int port, String name) {
if (this.connected) {
throw new IllegalStateException("已經連線");
}
this.connected = true;
this.name = name;
}
@Override
public void join(String room) {
requireConnected();
this.rooms.add(room);
}
@Override
public void say(String room, String text) {
requireConnected();
if (!this.rooms.contains(room)) {
for (Listener l : this.listeners) {
l.onError(403, "not in room " + room); // 模擬伺服器回 ERR
}
return;
}
for (Listener l : this.listeners) { // 模擬伺服器把訊息廣播回來
l.onMessage(room, this.name, text);
}
}
@Override
public void disconnect() {
requireConnected();
this.connected = false;
for (Listener l : this.listeners) {
l.onDisconnected();
}
}
@Override
public boolean isConnected() {
return this.connected;
}
private void requireConnected() {
if (!this.connected) {
throw new IllegalStateException("尚未連線");
}
}
}
Related articles
Angelia
haskell
Updated 2026-02-03
Adding.hs
Adding.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Adding.hs).
Read article →
Angelia
haskell
Updated 2026-02-03
Area.hs
Area.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Area.hs).
Read article →
Angelia
haskell
Updated 2026-02-03
Chess.hs
Chess.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Chess.hs).
Read article →
Angelia
haskell
Updated 2026-02-03
ChessGraphics.hs
ChessGraphics.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/ChessGraphics.hs).
Read article →
Angelia
haskell
Updated 2026-02-03
Examples.hs
Examples.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Examples.hs).
Read article →
Angelia
haskell
Updated 2026-02-03
Fibonacci.hs
Fibonacci.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Fibonacci.hs).
Read article →