OC學習日記014-單例模式和委託模式

設計模式(用來解決某一特定問題的):
觀察者模式|單例模式|委託模式|工廠模式

單例模式:

什麼時候使用單例模式?

 在一個工程中,一些類只需要一個實例變量的時候,我們就可以將這些類設計成單例模式

單例模式的作用?

 當一個‘類A’被設計成單例模式時,由‘類A’構造出的實例對象至於其他類來講爲全局實例對象,即在每一個類中由‘A’構造出的實例對象,都爲相同的對象。
 單例模式的實現思路:一個類只能創建一個實例和一個獲得該實例的方法
 在OC中如何將一個類設計成單例模式?
 1.在要被設計成單例的類的.h文件中聲明一個構造單例方法
 2.實現該方法

新建Student類,在Student.h文件中 聲明一個shareInstance方法:

 @interface Student : NSObject<NSCopying>
+(Student *)shareInstance;
@end

在Student.m文件中我們要首先聲明一個靜態實例對象,然後實現單例方法:

//聲明一個靜態的實例對象,只會在第一次執行
static Student *st=nil;

@implementation Student
//實現該方法
+(Student *)shareInstance{
    if (st == nil) {
        st =[[Student alloc]init];
    }
    return st;
}
//爲了防止alloc 或 new 創建新的實例變量
+(id)allocWithZone:(struct _NSZone *)zone{
    /*
    創建一個互斥鎖,保證此時沒有其他線程對self對象進行修改,起到線程保護作用。
     */
    @synchronized (self) {
        if (st == nil) {
            st=[super allocWithZone:zone];
        }
    }
    return st;
}
//爲了防止copy產生新的對象,需要遵循NSCopying

-(id)copyWithZone:(NSZone *)zone{
    return self;
}
@end

最後我們在主函數中測試建立不同的Student類的對象,我們會發現,它們儘管名字是不同的,它們實際上指針指向的地址還是一樣的:

    Student *student1=[Student shareInstance];
    Student *student2=[[Student alloc]init];
    Student *student3=[Student new];    
    Student *student4=[student3 copy];    NSLog(@"%p,%p,%p,%p",student1,student2,student3,student4);

委託模式

委託模式其實我們在上一篇文章協議也是有提到的,其實我們可以把它理解爲協議的一種使用形式。

概念:

 兩個對象間不能夠直接聯繫需要通過一個第三方對象,幫助他們聯繫,這一種模式,我們稱之爲‘委託模式’。

例子:

下面我們以房東委託中介賣房這種形式去說明一下:
我們先把他們之間的關係列出:

房東-委託->‘中介’-賣房->‘消費者’

這裏寫圖片描述
LandLord *landLord=[[LandLord alloc]init];
HouseSaler *houseSaler=[[HouseSaler alloc]init];
landLord.delegate=houseSaler;
houseSaler.landlord=landLord;
[landLord registerHouse];
@protocol LandLord_Protocol
-(void)mustSalerhHouse;
-(void)payMoney;
@end

import

import “LandLord_Protocol.h”

@interface LandLord : NSObject
//這裏使用assign或者weak是爲了防止循環引用
@property (nonatomic,assign)id delegate;
-(void)registerHouse;
//新增方法,表示房東收到錢
-(void)receiveMoney;
@end

import “LandLord.h”

@implementation LandLord

-(void)registerHouse{
NSLog(@”我是房東,我已經把房子登記到中介處”);
//如果委託存在,並且遵循制定協議
if (self.delegate && [self.delegate conformsToProtocol:@protocol(LandLord_Protocol)]) {
[self.delegate mustSalerhHouse];
[self.delegate payMoney];
}
}

-(void)receiveMoney{
NSLog(@”我是房東,我收到錢了”);
}
@end

import

import “LandLord_Protocol.h”

import “LandLord.h”

@interface HouseSaler : NSObject
@property (nonatomic,strong)LandLord *landlord;
@end

import “HouseSaler.h”

@implementation HouseSaler

-(void)mustSalerhHouse{
NSLog(@”我是中介,我跟房東簽訂了協議,我必須給房東賣房”);
}

-(void)payMoney{
NSLog(@”我是中介,我賣掉房子了,我抽了佣金,剩下的錢給你”);
[self.landlord receiveMoney];
}
@end

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章