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

来源:互联网 发布:人工智能创造新就业 编辑:程序博客网 时间:2024/05/21 08:29

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

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

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


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

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

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

@end

Buyer.m
#import"Buyer.h"

@implementationBuyer

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

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

@end

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

@protocolPaymentDelegate <NSObject>

-(
void)payment:(float)money;

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

@interfaceMediation : NSObject

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

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

@end

Meidition.m

#import"Mediation.h"

@implementationMediation

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

@end

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

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

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

staticStudent*stu = nil;

@implementationStudent

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

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

+(
instancetype)allocWithZone:(struct_NSZone*)zone{
   
if (stu== nil) {
       
stu = [superallocWithZone:zone];
    }
   
return stu;
}

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

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

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

@end

0 0
原创粉丝点击