swift - The Proxy Pattern

I describe the proxy pattern in this chapter, which is used when an object is required to act as an interface to another object or resource. There are three main ways in which the proxy pattern is applied, and I describe each of them and show you how to implement them. 


Xcode Foundation的经典delegate亦复如是。

我在实际工作中vc也仿照过Foundation的delegate:

button:内涵业务逻辑,底层实现;每个button是一个类,业务逻辑需要未知的参数和处理之后未知的结果反馈

UI:点击button之后界面的改变,UI实现未知的参数未知的结果反馈,也就是实现这个代理

这样以来UI的定制,很灵活很容易,代码思路依然清晰如初。


哪个是主体哪个是代理并不重要关键是看定义所说which is used when an object is required to act as an interface to another object or resource.

这个代理模式是结构模式中的一种,所以使用这个模式之后代码结构会非常清晰。


client:

import Foundation;


let url = "http://www.apress.com";

let headers = ["Content-Length","Content-Encoding"];


let proxy = AccessControlProxy(url: url);


for headerinheaders {

   proxy.getHeader(header, callback: {header, valin

       if (val !=nil) {

           println("\(header):\(val!)");

        }

    });

}


UserAuthentication.sharedInstance.authenticate("bob", pass:"secret");

proxy.execute();


NSFileHandle.fileHandleWithStandardInput().availableData;



/////////////////////////////////

pattern:

//1

import Foundation;


protocol HttpHeaderRequest {

    

   init(url:String);

   func getHeader(header:String, callback:(String,String?) -> Void );

   func execute();

}


class AccessControlProxy :HttpHeaderRequest {

   privatelet wrappedObject:HttpHeaderRequest;

    

   requiredinit(url:String) {

       wrappedObject =HttpHeaderRequestProxy(url: url);

    }

    

   func getHeader(header:String, callback: (String,String?) -> Void) {

       wrappedObject.getHeader(header, callback: callback);

    }

    

   func execute() {

       if (UserAuthentication.sharedInstance.authenticated) {

           wrappedObject.execute();

        }else {

           fatalError("Unauthorized");

        }

    }

}


privateclass HttpHeaderRequestProxy :HttpHeaderRequest {

   let url:String;

   var headersRequired:[String: (String,String?) -> Void];

    

   requiredinit(url:String) {

       self.url = url;

        self.headersRequired =Dictionary<String, (String,String?) ->Void>();

    }

    

   func getHeader(header:String, callback: (String,String?) -> Void) {

       self.headersRequired[header] = callback;

    }

    

   func execute() {

       let nsUrl =NSURL(string:url);

       let request =NSURLRequest(URL: nsUrl!);

        NSURLSession.sharedSession().dataTaskWithRequest(request,

            completionHandler: {data, response, errorin

               iflet httpResponse = responseas?NSHTTPURLResponse {

                   let headers = httpResponse.allHeaderFieldsas! [String:String];

                   for (header, callback)in self.headersRequired {

                        callback(header, headers[header]);

                    }

                }

        }).resume();

    }

}



//2

class UserAuthentication {

   var user:String?;

   var authenticated:Bool =false;

    

    private init() {

        // do nothing - stops instances being created

    }

    

   func authenticate(user:String, pass:String) {

       if (pass =="secret") {

           self.user = user;

           self.authenticated =true;

        }else {

           self.user =nil;

           self.authenticated =false;

        }

    }

    

   classvar sharedInstance:UserAuthentication {

       get {

           struct singletonWrapper {

               staticlet singleton =UserAuthentication();

            }

           returnsingletonWrapper.singleton;

        }

    }

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值