2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftでデザインパターン【Façade】

Last updated at Posted at 2020-08-20

元ネタ → ochococo/Design-Patterns-In-Swift

クラス図

image.png

図の引用元:Wikipedia: Facade パターン

概要

The facade pattern is used to define a simplified interface to a more complex subsystem.
Facadeパターンはより複雑なサブシステムへの簡略化されたインターフェイスを定義するために使用される。
クラス図のModuleA,B,Cmore complex subsystemに相当する。

サンプルコード

// Facade
final class Defaults {

	// ModuleA( more complex subsystem )
	private let defaults: UserDefaults
	
	init(defaults: UserDefaults = .standard) {
		self.defaults = defaults
		// 実質.standard以外ないので、initを書かずに以下のようなプロパティを書いても良い気がする。
		// private let defaults: UserDefaults = .standard
	}

	// subscript: instance["hoge"]のような記述ででアクセスできるようになる
	// simplified interface
	subscript(key: String) -> String? {
		// ここのUserDefaultsにアクセスする際の癖をラップして簡略化
		get {
			return defaults.string(forKey: key)
		}	
		set {
			defaults.set(newValue, forKey: key)
		}
	}
}

// usage //

let storage = Defaults()

// Store
// 何かの台詞だろうか。
storage["Bishop"] = "Disconnect me. I’d rather be nothing"

// Read
storage["Bishop"]

クラス図との対応

サンプルコード クラス図
Defaults Facade
UserDefaults ModuleA

考察

UserDefaultへの値の出し入れが少々癖がありより複雑なシステムであるところを、subscriptによってinstance[hoge]という書式で値の出し入れができる簡略化されたインタフェースに置き換えている。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?