<大话设计模式-p57>
今天是代理模式的代码
来看看不用代理的情况下代码的写法
//追求者类
class Pursuit: NSObject {
var mm:SchoolGirl?
init(mm:SchoolGirl) {
self.mm = mm
}
func giveDolls(){
print("\(mm!.name)送你洋娃娃")
}
func giveFlowers(){
print("\(mm!.name)送你鲜花")
}
func giveChocolate(){
print("\(mm!.name)送你巧克力")
}
}
//被追求者类
class SchoolGirl: NSObject {
private var _name:String = ""
var name:String {
set {
_name = newValue
}
get {
return _name
}
}
}
//客户端代码
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let tong = SchoolGirl()
tong.name = "僮"
let wang = Pursuit(mm: tong) // 女孩并不认识男孩, 因此此处写法有问题
wang.giveDolls()
wang.giveChocolate()
wang.giveFlowers()
}
}
// 僮送你洋娃娃
// 僮送你巧克力
// 僮送你鲜花
仅仅有代理的代码
// 代理类
class Proxy: NSObject {
var mm:SchoolGirl?
init(mm:SchoolGirl) {
self.mm = mm
}
func giveDolls(){
print("\(mm!.name)送你洋娃娃")
}
func giveFlowers(){
print("\(mm!.name)送你鲜花")
}
func giveChocolate(){
print("\(mm!.name)送你巧克力")
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let tong = SchoolGirl()
tong.name = "僮"
let firend = Proxy(mm: tong)
firend.giveDolls()
firend.giveChocolate()
firend.giveFlowers()
}
}
但这样的话仅仅是把代理类写出来了, 但是追求者消失了, 代码中应该三方都是存在的
使用代理模式实现
// 代理方法(协议)
protocol IGiveGiftDelegate {
func giveDolls()
func giveFlowers()
func giveChocolate()
}
// 追求者类(被代理类)
class Pursuit: NSObject, IGiveGiftDelegate {
var mm:SchoolGirl?
init(mm:SchoolGirl) {
self.mm = mm
}
// 实现代理的方法
func giveDolls(){
print("\(mm!.name)送你洋娃娃")
}
func giveFlowers(){
print("\(mm!.name)送你鲜花")
}
func giveChocolate(){
print("\(mm!.name)送你巧克力")
}
}
// 代理类
class Proxy: NSObject, IGiveGiftDelegate {
var gg:Pursuit?
init(mm:SchoolGirl) {
self.gg = Pursuit(mm: mm)
}
func giveFlowers() {
gg?.giveFlowers()
}
func giveDolls() {
gg?.giveDolls()
}
func giveChocolate() {
gg?.giveChocolate()
}
}
//客户端代码
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let tong = SchoolGirl()
tong.name = "僮"
let firend = Proxy(mm: tong)
firend.giveDolls()
firend.giveChocolate()
firend.giveFlowers()
}
}
这样将追求者与被追求者 和代理者(电灯泡)都独立开了
这也是我在写代码中最长用到的一种设计模式了, 慢慢体会一下