UI学习 第九章 委托(代理)设计模式      单例设计模式

UI学习    第九章      委托(代理)设计模式      单例设计模式

委托(代理)设计模式
一个人找中介买房子为例
main.m
#import <Foundation/Foundation.h>
#import
"Buyer.h"

int main( int argc, const char * argv[]) {
   
@autoreleasepool {
       
// 假设有一个人需要房子,这个人找到中介就行
       
Buyer *buyer = [[ Buyer alloc ] init ];
        [buyer
findMediation ];
    }
   
return 0 ;
}


Buyer.h
#import <Foundation/Foundation.h>
#import
"Mediation.h"

@interface Buyer : NSObject < PaymentDelegate > // 要找房子必须要签协议

-(
void )findMediation; // 我要找一个中介

@end

Buyer.m
#import "Buyer.h"

@implementation Buyer

-(
void )findMediation{ // 去找中介,让中介帮我找房源
   
NSLog ( @" 我需要房源 " );
   
   
Mediation *m = [[ Mediation alloc ] init ]; // 找到中介了
    m.
delegate = self ; // 跟中介签协议的是我,不能忘记写
    [m
handle ]; // 中介帮我找房子了
}

-(
void )payment:( float )money{ // 中介让我付钱
   
NSLog ( @" 付钱 :%.2f" ,money);
}

@end

Meidition.h
// 在被委托者的声明文件 (.h) 中进行协议的声明
#import <Foundation/Foundation.h>

@protocol PaymentDelegate < NSObject >

-(
void )payment:( float )money;

@end // 这是一个协议 , 在被委托者的声明文件 (.h) 中进行协议的声明

@interface Mediation : NSObject

@property ( nonatomic , weak ) id < PaymentDelegate > delegate; // 是谁给我签了协议

-(
void )handle; // 我得有找做一些事情的能力

@end

Meidition.m

#import "Mediation.h"

@implementation Mediation

-(
void )handle{ // 找到房源了
   
NSLog ( @" 找到房源,请给钱 " );
   
    [
_delegate payment : 10.0 ]; // 我得问签协议的那个人要我的房钱
}

@end

委托主要作用:
1.回传值
2.当我们声明一个遵循了协议的属性时,属性的关键字要用,weak,assing,目的是为了避免循环引用,
3.委托最大的特点一对一。
4.委托一般是具有上下级关系的两个类

委托怎么用??
第一步:首先在被委托的那个类的.m文件里声明一个协议(也可单独建一个文件,不过不常用),协议中的方法是要做的事情。
第二步:让委托者遵守这个协议。
第三部:让被委托者做事情。 很多时候需要在被委托者类里进行赋值并且回传,如:
        [ _delegate addCell : name . text : phone . text ];
    [self.navigationController popViewControllerAnimated:YES];
第四部:让委托者实现这个协议方法。

单例设计模式
如果不使用单例,每次alloc init 都会产生一个新的对象,如果使用单例,重写初始化方法,那么每次初始化的对象都是同一个对象。
#import "Student.h"

static Student *stu = nil ;

@implementation Student

+(
Student *)shareStudent{
   
   
@synchronized ( self ){ // 避免多线程操作带来的弊端
       
if ( stu == nil ) {
           
stu = [[ Student alloc ] init ];
        }
       
return stu ;
    }
}

// 避免 alloc 产生新对象 重写 alloc 方法

+(
instancetype )allocWithZone:( struct _NSZone *)zone{
   
if ( stu == nil ) {
       
stu = [ super allocWithZone :zone];
    }
   
return stu ;
}

// 避免 copy 新对象,重写 copy 方法

-(
id )copyWithZone:( NSZone *)zone{
   
return stu ;
}

-(
id )mutableCopyWithZone:( NSZone *)zone{
   
return stu ;
}

@end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值