ViewController.m
#import "ViewController.h"
#import "HouseSaler.h"
#import "Landlord.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*
委托模式
两个对象间不能够直接联系,需要通过一个第三方对象,帮助他们联系,这一种模式,我们称之为'委托模式'
如何在OC中使用委托模式?在OC中实现委托模式需要OC中的一个元素'protocol',即协议
*/
HouseSaler *houseSaler = [HouseSaler new];
Landlord *landloard = [Landlord new];
landloard.delegate = houseSaler ;
houseSaler.customer = landloard ;
[landloard registerHouse];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
Landlord_Protocol.h
#import <Foundation/Foundation.h>
@protocol Landlord_Protocol <NSObject>
@required
-(void)mustSaleHouse ;
-(void)payMoney ;
@end
HouseSaler.h
#import <Foundation/Foundation.h>
#import "Landlord_Protocol.h"
#import "Landlord.h"
@interface HouseSaler : NSObject <Landlord_Protocol>
@property (nonatomic,assign)Landlord *customer ;
-(void)saleHouse;
@end
=========================================================HouseSaler.m
#import "HouseSaler.h"
@implementation HouseSaler
-(void)saleHouse
{
NSLog(@"我是中介,我替卖家卖房子");
}
//实现协议里卖房子的方法
-(void)mustSaleHouse
{
NSLog(@"我是中介,我与房东签了协议,我必须替房东卖掉房子");
}
-(void)payMoney
{
NSLog(@"我是中介,我卖房子了,钱我给你了");
[self.customer receiveMoney];
}
@end
=============================================================Landlord.h
#import <Foundation/Foundation.h>
//#import "HouseSaler.h"
@class HouseSaler;
#import "Landlord_Protocol.h"
@interface Landlord : NSObject
//1.这是最简单的委托模式
//这里使用assign 是为了防止循环引用
@property (nonatomic,assign) HouseSaler *delegate;
//使用正式协议的委托模式
//@property (nonatomic,assign) id <Landlord_Protocol> delegate;
-(void)registerHouse;
//用于表示房东收到款了
-(void)receiveMoney ;
@end
=====================================================================Landlord.m
#import "Landlord.h"
#import "HouseSaler.h"
@implementation Landlord
-(void)registerHouse
{
NSLog(@"我是房东,我已经将房子登记到中介处了");
//如果委托存在,调用委托的方法
// if (self.delegate)
// {
// [self.delegate saleHouse];
// }
//如果委托存在并且委托遵循指定协议
if (self.delegate && [self.delegate conformsToProtocol:@protocol(Landlord_Protocol)])
{
[self.delegate mustSaleHouse];
[self.delegate payMoney];
}
}
-(void)receiveMoney
{
NSLog(@"我是房东,我收到钱了");
}
@end