[iOS]使用NSProxy實現代理模式

來源:互聯網
上載者:User

// MyProxy.h

#import
<Foundation/Foundation.h>

@interface MyProxy :
NSProxy {

   
NSObject *object;

}

- (id)transformToObject:(NSObject *)anObject;

@end

// MyProxy.m

#import
"MyProxy.h"

@implementation MyProxy

- (void)dealloc

{

    [object
release];

   
object = nil;

    [super
dealloc];

}

- (void)fun

{

   
// Do someting virtual

    //
先做一些代理工作,然後建立一個後台線程,在後台線程中再調用真正的[object fun];

}

// Stupid transform implementation just by assigning a passed in object as transformation target. You can write your factory here and use passed in object as id for object that need
ot be created.

- (id)transformToObject:(NSObject *)anObject 

{

   
if(object != anObject) {

        [object
release];

    }

   
object = [anObject retain];

   
return object;

}

- (void)forwardInvocation:(NSInvocation *)invocation 

{

   
if (object !=
nil) {

        [invocation
setTarget:object];    

        

        [invocation
invoke];

    }

}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel 

{

   
NSMethodSignature *result;

   
if (object !=
nil) {

        result = [object
methodSignatureForSelector:sel];

    }
else {

       
// Will throw an exception as default implementation

        result = [super
methodSignatureForSelector:sel];

    }

   
return result;

}

@end

// RealSubject.h

#import
<Foundation/Foundation.h>

@implementation RealSubject : NSObject

- (void)fun;

@end

// RealSubject.m

#import
"RealSubject.h"

@implementation RealSubject

- (void)fun

{

    //
這個方法需要代理進行惰性調用

   
// Do something real

}

- (void)otherFun

{

    //
這個方法不需要代理做任何處理,可直接被調用

   
// Do something real

}

@end

// main.m

int main(int argc,
char *argv[]) 

{

   
NSAutoreleasePool * pool = [[NSAutoreleasePool
alloc]
init];

   
MyProxy *myProxy = [MyProxy
alloc];

   
RealSubject *realSub = [[RealSubject
alloc] init];

    [myProxy
transformToObject:realSub];

    [myProxy
fun];
// 直接調用myProxy的fun,執行代理工作

    [myProxy
otherFun];
// 依次調用myProxy的methodSignatureForSelector和forwardInvocation轉寄給realSub,realSub調用otherFun

    [realSubject
release];

    [myProxy
release];

    [pool
release];

   
return 0;

}


注意,調用MyProxy中未定義的方法otherFun會出現'MyProxy' may not respond to 'fun'的警告,可通過使用私人範疇或通過performSelector:withObject:來避免,如果有更好的方法,請告知。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.