시리즈: Angelia
java
62 줄
· 업데이트 2026-09-27
Main.java
Angelia/Java/Week_6_7/code/02_adt_interfaces/Main.java
/**
* 02_adt_interfaces 示範程式。
*
* 編譯與執行:
* javac *.java
* java -ea Main
*/
public class Main {
/**
* 這個函式只認識 ChatHistory 介面。
* 傳進來的是環狀緩衝區或鏈結串列,它完全不在乎——這就是「解耦」(decoupling)。
*/
static void simulateChat(ChatHistory history) {
history.addMessage("Alice: 嗨!");
history.addMessage("Bob: 你好~");
history.addMessage("Alice: 週六要一起讀 Java 嗎?");
history.addMessage("Bob: 好啊,下午兩點圖書館見。");
System.out.println(" (共 " + history.size() + " 則,最新在前)");
history.display();
}
public static void main(String[] args) {
System.out.println("=== 1. 同一段程式碼,兩種實作 ===");
System.out.println("[鏈結串列:全部保留]");
simulateChat(new LinkedListChatHistory());
System.out.println("[環狀緩衝區:只留最近 3 則]");
simulateChat(new CircularBufferChatHistory(3));
System.out.println("=== 2. 宣告型別決定你能呼叫什麼 ===");
ChatHistory h1 = new LinkedListChatHistory();
h1.addMessage("hello");
// h1.erase(); // 編譯錯誤!h1 的宣告型別是 ChatHistory,裡面沒有 erase()
ErasableChatHistory h2 = new LinkedListChatHistory();
h2.addMessage("hello");
h2.erase(); // OK:ErasableChatHistory 有 erase()
assert h2.size() == 0;
System.out.println(" erase 之後 size = " + h2.size());
System.out.println("=== 3. List ADT:LinkedSimpleList ===");
SimpleList list = new LinkedSimpleList();
list.add("apple");
list.add("banana");
list.add("cherry");
System.out.println(" " + list + ",size = " + list.size());
assert list.size() == 3;
assert list.get(1).equals("banana");
list.remove("banana");
System.out.println(" 移除 banana → " + list);
assert list.size() == 2 && list.get(1).equals("cherry");
list.remove("not-there"); // 不存在:什麼都不做
assert list.size() == 2;
list.remove("apple"); // 移除第一個節點
assert list.get(0).equals("cherry");
try {
list.get(5);
} catch (IndexOutOfBoundsException e) {
System.out.println(" 攔到 IndexOutOfBoundsException:" + e.getMessage());
}
System.out.println("全部完成。");
}
}
관련 글
Angelia
haskell
EN
업데이트 2026-02-03
Adding.hs
Adding.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Adding.hs).
글 읽기 →
Angelia
haskell
EN
업데이트 2026-02-03
Area.hs
Area.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Area.hs).
글 읽기 →
Angelia
haskell
EN
업데이트 2026-02-03
Chess.hs
Chess.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Chess.hs).
글 읽기 →
Angelia
haskell
EN
업데이트 2026-02-03
ChessGraphics.hs
ChessGraphics.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/ChessGraphics.hs).
글 읽기 →
Angelia
haskell
EN
업데이트 2026-02-03
Examples.hs
Examples.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Examples.hs).
글 읽기 →
Angelia
haskell
EN
업데이트 2026-02-03
Fibonacci.hs
Fibonacci.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Fibonacci.hs).
글 읽기 →