- 设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。
1、单例-sharedXxx
- 单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。
// 保证对象只被初始化一次
+ (instancetype)sharedXxxxTools {
// GCD
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
- 自定义单例,不用多线程:
+(id)shareDefault
{
static id s;
if(s==nil)
{
s=[[self alloc] init]
}
return s;
}
PS:
- 1、保证对象只被分配一次内存空间,通过dispatch_once能够保证单例的分配和初始化是线程安全的
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
// 同上
}
- 2、当使用到 copy 时,调用。
// 如:NSMutableDictionary 的 key,会默认做一次 copy 操作
- (id)copyWithZone:(NSZone *)zone {
return instance;
}
2、代理-delegate/protocol
- 代理设计模式:为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。
模式结构:一个是真正的你要访问的对象(目标类),一个是代理对象,真正对象与代理对象实现同一个接口,先访问代理类再访问真正要访问的对象。
a. 定义协议、方法 & 属性(Person.h)
@class Person;
@protocol PersonDelegate <NSObject>
- (void)personFightWithOthers:(Person *)person;
@end
@interface Person : NSObject
@property (nonatomic, strong) id<PersonDelegate> delegate;
- (void)fight;
@end
- b. 遵守协议,成为代理,实现方法(Person.m)
- (void)fight
{
if ([self.delegate respondsToSelector:@selector(personFightWithOthers:)]) {
[self.delegate teacherFightWithOthers:self];
}
}
- Student.m
@interface Student() <TeacherDelegate>
@end
- (void)personFightWithOthers:(Person *)person
{
NSLog(@"fight...");
}
3、通知-Notification
- Key-Value Coding (KVC):即是指 NSKeyValueCoding
- 一个非正式的 Protocol,提供一种机制来间接访问对象的属性
- Key-Value Observing (KVO) :监听对象的属性值变化
- 它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。每次指定的被观察的对象的属性被修改后,KVO自动通知相应的观察者。
观察者模式
- 什么时候使用观察者模式?
- 当你需要将改变通知所有的对象时,而你又不知道这些对象的具体类型,此时就可以使用观察者模式。 改变发生在同一个对象中,并在别的地方需要将相关的状态进行更新。
- iOS中观察者模式的实现方法
- 在iOS中观察者模式的实现有三种方法:Notification、KVO以及标准方法。
- // 添加观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextFieldTextDidChangeNotification object:nil];
- // 移除观察者
[[NSNotificationCenter defaultCenter] removeObserver:self];
- // 发送监听
[[NSNotificationCenter defaultCenter] postNotificationName:UITextFieldTextDidChangeNotification object:@"----!!!!" userInfo:@{@"username": @"zhangsan"}];
- 本地通知:
// 1.创建本地通知对象
UILocalNotification *note = [[UILocalNotification alloc] init];
// 注册通知时,指定需要传递的数据
note.userInfo = @{@"name":@"mb",@"age":@"22",@"phone": @"1234567890"};
// 2.注册通知
UIApplication *app = [UIApplication sharedApplication];
// 将通知添加到scheduledLocalNotifications数组中
[app scheduleLocalNotification:note];