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;
}
}
}