初学者,自用笔记

把一个已有类/接口(Adaptee)的能力,包装成客户端期望的接口(Target),从而在不修改已有代码的前提下完成兼容与复用

  • Target:客户端期望的接口(你希望系统统一调用的样子)
  • Adaptee:已有的、不兼容的类/接口(第三方库/旧系统/历史代码)
  • Adapter:适配器,实现 Target,并在内部调用 Adaptee 完成转换

Target

public interface IGameObjectStorage
{
    void Save(string path, GameObject go);
    GameObject Load(string path);
}

Adaptee

// -------------------- Adaptee 1:JSON 存储(接口形状与 XML 不同) --------------------
public sealed class JsonStore
{
    public void WriteToFile(string path, GameObjectDto dto)
    {
        // Unity 内置 JsonUtility
        string json = JsonUtility.ToJson(dto, prettyPrint: true);
        File.WriteAllText(path, json, Encoding.UTF8);
    }

    public GameObjectDto ReadFromFile(string path)
    {
        string json = File.ReadAllText(path, Encoding.UTF8);
        return JsonUtility.FromJson<GameObjectDto>(json);
    }
}

// -------------------- Adaptee 2:XML 存储(另一套实现) --------------------
public sealed class XmlStore
{
    public void Serialize(string path, GameObjectDto dto)
    {
        var serializer = new XmlSerializer(typeof(GameObjectDto));
        using (var fs = File.Create(path))
        {
            serializer.Serialize(fs, dto);
        }
    }

    public GameObjectDto Deserialize(string path)
    {
        var serializer = new XmlSerializer(typeof(GameObjectDto));
        using (var fs = File.OpenRead(path))
        {
            return (GameObjectDto)serializer.Deserialize(fs);
        }
    }
}

Adapter

// -------------------- Adapter:把 JSON 存储适配成 IGameObjectStorage --------------------
public sealed class JsonStorageAdapter : IGameObjectStorage
{
    private readonly JsonStore _json;

    public JsonStorageAdapter(JsonStore json) => _json = json;

    public void Save(string path, GameObject go)
    {
        var dto = GameObjectDto.FromGameObject(go);
        _json.WriteToFile(path, dto);
    }

    public GameObject Load(string path)
    {
        var dto = _json.ReadFromFile(path);
        var go = new GameObject(dto.name);
        dto.ApplyTo(go);
        return go;
    }
}

// -------------------- Adapter:把 XML 存储适配成 IGameObjectStorage --------------------
public sealed class XmlStorageAdapter : IGameObjectStorage
{
    private readonly XmlStore _xml;

    public XmlStorageAdapter(XmlStore xml) => _xml = xml;

    public void Save(string path, GameObject go)
    {
        var dto = GameObjectDto.FromGameObject(go);
        _xml.Serialize(path, dto);
    }

    public GameObject Load(string path)
    {
        var dto = _xml.Deserialize(path);
        var go = new GameObject(dto.name);
        dto.ApplyTo(go);
        return go;
    }
}