[單例、代理 & 通知]

  • 設計模式(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];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章