商品列表頁(ListView/RecyclerView)已通過 JSON 解析填充數據,每項含「加入購物車」按鈕。點擊後需將選中商品信息傳遞到購物車/結算 Activity 顯示。
| 方案 | 核心機制 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|---|
| 1. Intent + Bundle/Parcelable (推薦) | 序列化對象放入 Bundle → putExtra → startActivity | 標準、進程隔離安全、支持進程間通信、生命周期受系統管理 | 數據量大時受 Binder 限制(~1MB)、需實現 Parcelable/Serializable | 大多數場景,特別是跨 Activity/進程 |
| 2. 單例/靜態持有類 | 全局靜態 Map/List 保存數據,目標頁直接讀取 | 代碼極簡、無大小限制、跨任意組件訪問 | 內存洩漏風險、進程重啟數據丟失、線程不安全、耦合度高、難測試 | 極簡原型、臨時數據、單進程小應用 |
| 3. 本地持久化 | Room/SQLite/SharedPreferences/File 存儲,傳遞 ID 查詢 | 數據持久化、跨進程/重啟可用、支持複雜查詢 | IO 開銷、代碼量大、需處理同步/遷移 | 購物車需持久化、多端同步、離線可用 |
// Java 版
public class Goods implements Parcelable {
private long id;
private String name;
private double price;
private int count;
// getter/setter/構造器
protected Goods(Parcel in) {
id = in.readLong();
name = in.readString();
price = in.readDouble();
count = in.readInt();
}
public static final Creator CREATOR = new Creator() {
@Override public Goods createFromParcel(Parcel in) { return new Goods(in); }
@Override public Goods[] newArray(int size) { return new Goods[size]; }
};
@Override public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(name);
dest.writeDouble(price);
dest.writeInt(count);
}
@Override public int describeContents() { return 0; }
}
// Kotlin 版 (一行搞定)
@Parcelize
data class Goods(
val id: Long,
val name: String,
val price: Double,
var count: Int
) : Parcelable
// 單個商品
Intent intent = new Intent(this, CartActivity.class);
intent.putExtra("goods", goods); // Parcelable 自動打包
startActivity(intent);
// 多個商品 (ArrayList)
intent.putParcelableArrayListExtra("goodsList", selectedGoodsList);
Goods goods = getIntent().getParcelableExtra("goods");
ArrayList list = getIntent().getParcelableArrayListExtra("goodsList");
// 單例管理器 (應用級)
public class CartManager {
private static CartManager instance;
private final Map cartMap = new ConcurrentHashMap<>();
public static CartManager get() { ... }
public void addGoods(Goods goods) { ... }
public List getAllGoods() { ... }
public void syncToLocal() { ... } // 異步持久化到 Room/SP
}
CartManager.get().addGoods() 操作;CartManager.get().getAllGoods() 或接收 Intent 數據;syncToLocal() 落地;CartManager 狀態。