// swift 3.0
// 作曲家の名刺
protocol ComposeDelegate {
func createSong(jenre:String)
}
// プロデューサーは作曲家の名刺を持っている
class Producer:ComposeDelegate {
var name:String
init(name:String) {
self.name = name
}
// 作曲(発注)のデリゲートメソッド
func createSong(jenre:String) {
print("\(self.name)さんは\(jenre)の作曲を依頼しました")
}
}
// JPop作曲家
class PopComposer {
var name:String
var delegate:ComposeDelegate? // 名刺ホルダー
init(name:String) {
self.name = name
}
func compose() {
if let _ = self.delegate {
delegate?.createSong(jenre: "JPop")
} else {
print("\(self.name)は作曲を依頼されてません")
}
}
}
// Dance作曲家
class DanceComposer {
var name:String
var delegate:ComposeDelegate?
init(name:String) {
self.name = name
}
func compose() {
if let _ = self.delegate {
delegate?.createSong(jenre: "Dance")
} else {
print("\(self.name)は作曲を依頼されてません")
}
}
}
let akimoto = Producer(name:"akimoto")
let komuro = PopComposer(name:"komuro")
let nakata = DanceComposer(name:"nakata")
komuro.compose()
komuro.delegate = akimoto // 名刺交換
komuro.compose()
nakata.compose()
nakata.delegate = akimoto // 名刺交換
nakata.compose()
/* 出力
komuroは作曲を依頼されてません
akimotoさんはJPopの作曲を依頼しました
nakataは作曲を依頼されてません
akimotoさんはDanceの作曲を依頼しました
*/
More than 5 years have passed since last update.
デリゲートパタン 〜 protocolを「名刺」に例えてみた 〜【Swift3.0】
Last updated at Posted at 2016-11-28
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
List of users who liked
48