定义
为其他对象提供一种代理以控制对这个对象的访问
结构
示例
Subject 定义了 RealSubject 和 Proxy 的公共接口,这样就可以在任何使用 RealSubject 的地方使用 Proxy。
1
2
3
| abstract class Subject { public abstract void Request();} |
1
2
3
4
5
6
| class RealSubject extends Subject { @Override public void Request() { System.out.println("真实的请求"); }} |
1
2
3
4
5
6
7
8
9
10
| class Proxy extends Subject { private RealSubject real; @Override public void Request() { if (null == real) { real = new RealSubject(); } real.Request(); }} |
样例
定义逻辑层接口协议:
1
2
3
| @protocol LogicInterface<NSObject>- (void)applicationLaunching; // 启动应用@end |
1
2
3
| @interface Logic : NSObject<LogicInterface> // 实现协议+ (id<LogicInterface>)getInstance;@end |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| static Logic *gStaticLogic = nil;@interface Logic()<LogicInterface> // 实现协议@property (nonatomic, strong)TcpModule *tcpModule;@end@implementation Logic+ (Logic *)getInstance { @synchronized(self) { if (gStaticLogic == nil) { gStaticLogic = [[Logic alloc]init]; } return gStaticLogic; }}- (void)applicationLaunching { // tcpModule 是真实的具体处理 module [self.tcpModule applicationLaunching];}@end |
1
2
| @interface HomeViewController : UIViewController @end |
1
2
3
4
5
| @implementation HomeViewController- (void)viewDidLoad { [[Logic getInstance]applicationLaunching];}@end |
转载请并标注: “本文转载自 linkedkeeper.com (文/张松然)”