Simplified the development of our applications, which is easy to implement and flexible
The following is a small example of renting a house to simulate the proxy mode.
(The House owner is: real role RealSubject; intermediary: Proxy role Proxy; as we are going to rent a house,
We usually do not see the house owner at ordinary times. At this time, we went to an intermediary to ask the intermediary to negotiate with the homeowner directly and rent the house,
An intermediary directly deals with house rental. The intermediary is the agent in the house rental process), see the structure:
1: Agreement statement:
#import
@protocol FindApartment
-(void)findApartment;@end
2: Agent role Declaration (Agent. h) header file Declaration
#import
#import "FindApartment.h"@interface Agent : NSObject
@end
3: Agent. m file
#import "Agent.h"@implementation Agent-(void)findApartment{ NSLog(@"findApartment");}@end
4: actual role Declaration (Person. h) header file Declaration
# Import
# Import "FindApartment. h" @ interface Person: NSObject {@ private NSString * _ name; id
_ Delegate; // The principal (with the protocol used by the intermediary to find the house)} @ property (nonatomic, copy) NSString * name; @ property (nonatomic, assign) id
Delegate;-(id) initWithName :( NSString *) name withDelegate :( id
) Delegate;-(void) wantToFindApartment; @ end
5: Real Role Implementation (Person. m)
# Import "Person. h "// defines the private method @ interface Person ()-(void) startFindApartment :( NSTimer *) timer; @ end @ implementation Person @ synthesize name = _ name; @ synthesize delegate = _ delegate;-(id) initWithName :( NSString *) name withDelegate :( id
) Delegate {self = [super init]; if (self) {self. name = name; self. delegate = delegate;} return self;}-(void) wantToFindApartment {[nst?scheduledtimerwithtimeinterval: 2 target: self selector: @ selector (startFindApartment :) userInfo: @ "Hello" repeats: YES];}-(void) startFindApartment :( NSTimer *) timer {// NSString * userInfo = [timer userInfo]; [self. delegate findApartment];} @ end
6: test the agent main. m METHOD
#import
#import "Person.h"#import "Agent.h"int main(int argc, const char * argv[]){ @autoreleasepool { // insert code here... NSLog(@"Hello, World!"); Agent *agent=[[Agent alloc]init]; Person *jack=[[Person alloc]initWithName:@"jack" withDelegate:agent]; [jack wantToFindApartment]; [[NSRunLoop currentRunLoop]run]; [jack autorelease]; } return 0;}