Adapter Pattern === --- ![](https://hackmd.io/_uploads/rJ_-8wEI3.png =400x400) --- # End (並沒有) --- ```mermaid flowchart LR ScamAdviser-->Lambda Google-->Lambda Crawler-->Lambda 165-->Lambda Lambda-->S3 S3-->DataPipeline DataPipeline-->DynamoDB ``` 每一種來源的 API 都不一樣 --- ```go package source type Provider interface { List(since time.Time) []RawData } ``` 統一成目標的介面 --- ```go package provider type ScamAdviser struct { api scamadviser.Client } func (p *ScamAdviser) List(since time.Time) []source.RawData { items := make([]source.RawData, 0) // ... item := p.api.Download(name) // ... return items } ``` 讓不同形狀的物件被統一 --- ```go package source func CopyFrom(provider Provider, dest s3.Client) error { items := provider.List() for _, item := range items { // ... } return nil } ``` 在使用端看起來就是一致的 --- ORM 大多具有 Adapter 特性 --- ```mermaid= flowchart LR Controller --> ActiveRecord ActiveRecord --> MySQL ActiveRecord --> PostgreSQL ActiveRecord --> SQLite ``` --- ```ruby= class UsersController < ApplicationController def index @users = User.where(created_at: Time.zone.now) end end ``` ActiveRecord 有統一的介面 e.g. `where` --- ```ruby= # config/database.yml default: adapter: sqlite3 # ... production: adapter: postgresql ``` ActiveRecord 可以透過設定檔指定 Adapter --- ```ruby= # Gemfile gem "pg" gem "activerecord" ``` `pg` 是資料庫客戶端, `activerecord` 作為 `pg` 的 Adapter 來統一行為 --- * 針對介面差異的處理 * 兩邊具有類似的性質 * 都是資料庫 * 都是同一種資料 用來處理不同後端(資料庫)、Legacy API 的過度 --- 跟 Proxy 的差異在於 Proxy 的介面是一致的 如:Reverse Proxy 的介面都是 HTTP Protocol
{"metaMigratedAt":"2023-06-18T05:50:34.120Z","metaMigratedFrom":"YAML","title":"Adapter Pattern","breaks":true,"contributors":"[{\"id\":\"f37d49bd-d692-405a-b768-5e0a6d63c524\",\"add\":1677,\"del\":0}]"}
    132 views