實作 Swift 設計模式
  • 前言
  • Swift 設計模式
  • 入門 - 開始
  • 設計模式之王 - MVC
    • 如何使用 MVC 模式
  • 簡易工廠模式 - Simple Factory
    • 如何使用簡易工廠模式
  • 外觀模式 - Facade
    • 如何使用外觀模式
  • 裝飾者模式 - Decorator
    • 擴展
    • 如何使用擴展
    • 委派
    • 如何使用委派模式
  • 單例模式 - Singleton
    • 如何使用單例模式
  • 適配器模式 - Adapter
    • 如何使用適配器模式
  • 觀察者模式 - Observer
    • 通知 - Notification
    • 鍵值觀察 - KVO
    • 事件流 - Event Flow
  • 設計模式之神話 - MVP
    • 如何使用 MVP 模式
    • 最後的潤色
  • 入門 - 小結
Powered by GitBook
On this page

Was this helpful?

  1. 簡易工廠模式 - Simple Factory

如何使用簡易工廠模式

以下是Flickr API的描述類別:

// FlickrAPI.swift
import Foundation

class FlickrAPI{
    static func flickrAPIUrl() ->String{
        return "https://api.flickr.com/services/rest/"
    }

    static func flickrInterestingness(aPageIndex:UInt = 1,aPerPage:UInt = 99) -> Dictionary<String,String> {
        let _paramters:Dictionary<String,String> = [
            "method"         : "flickr.interestingness.getList",
            "api_key"        : "your_flickr_api_key",
            "per_page"       : "\(aPerPage)",
            "format"         : "json",
            "nojsoncallback" : "1",
            "extras"         : "url_q,url_z",
            "page"           : "\(aPageIndex)"
        ]
        return _paramters
    }
}

原則上,簡易工廠模式下,都是 static 的 func ,而且都會回傳一個「類別實體」,像上面的flickrAPIUrl嚴格來說,也不能算是簡易工廠模式,因為String屬於基本型別,而且也不是自定義的類別,而且FlickrAPI本身並沒有實體化的需求。

筆者只是透過FlickrAPI這類別對大家做一下基本架構的展現而已。

像之前的LionCofe才是典型的簡易工廠設計模式,另外 Apple 提供的 API 下,最典型的簡易工廠模式則是 UIColor。

完成到這一步的Demo:

  • 查看原始碼

Previous簡易工廠模式 - Simple FactoryNext外觀模式 - Facade

Last updated 6 years ago

Was this helpful?

Flickr API 申請網址:

https://www.flickr.com/services/api/
下載ZIP