一.单例(Singleton)

单例模式是一种常见的模式,它的本质就是声明一个全局变量/对象。

在iOS中典型的单例模式就是[NSNotificationCenter defaultCenter],[UIColor redColor]等。

单例模式的优点是,可以延迟加载,按需分配内存以节省开销,但是需要注意的是不能滥用该模式否则反而造成内存的损耗。

下面使用GCD来实现一个单例模式,可以保证线程安全。

/* Singleton.h */
#import <Foundation/Foundation.h>

@interface Singleton : NSObject
+ (Singleton *)sharedInstance;
@end

/* Singleton.m */
#import "Singleton.h"

static Singleton *instance = nil; // 声明全局对象指针

@implementation Singleton 

+ (Singleton *)sharedInstance { 
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        instance = [[Singleton alloc] init];
    });
    return instance; 
}

@end

二.工厂模式(Factory)

工厂模式是另一种常见的设计模式,本质上是使用该模式来简化类的选择和初始化过程。

//
//  OperationFactory.m
//  FactoryPattern

#import "OperationFactory.h"
#import "Operation.h"
#import "OperationAdd.h"
#import "OperationSub.h"
#import "OperationMul.h"
#import "OperationDiv.h"

@implementation OperationFactory

+ (Operation *) createOperate:(char)operate{
    Operation *oper = nil;
    switch (operate) {
        case '+':
        {
            oper = [[OperationAdd alloc] init];
            break;
        }
        case '-':
        {
            oper = [[OperationSub alloc] init];
            break;
        }
        case '*':
        {
            oper = [[OperationMul alloc] init];
            break;
        }
        case '/':
        {
            oper = [[OperationDiv alloc] init];
            break;
        }
        default:
            break;
    }
    return oper;
}
@end

由于 Objective-C 本身的动态特性,还可以用反射来改写:

@implementation OperationFactory
+ (Operation *) createOperate:(NSString *)operate{
    Operation *oper = nil;
    Class class = NSClassFromString(operate);
    oper = [(Operation *)[class alloc] init];
    return oper;
}
@end

使用时,可以传入类名,来获取对应类的对象:

Operation *oper = [OperationFactory createOperate: @"OperationAdd"];
oper.numberA = 10;
oper.numberB = 20;
NSLog(@"%f", oper.getResult);

三.委托模式(Delegate)

在 Objective-C 中,委托模式通常使用协议(protocol)来实现。该模式是一种十分常见的设计模式,用于代码的解耦合,同时在iOS中用来替代多重继承的特性。

@protocol AClassPrintDelegate <NSObject>
@required
- (void)printHello;
@end

@interface AClass : NSObject
@property id<AClassPrintDelegate> delegate;
@end

@implementation AClass

-(void)hello {
    self.delegate = [[BClass alloc] init];
    [self.delegate print];
}
@end
@interface BClass : NSObject <AClassPrintDelegate>

@end

@implementation BClass

#parm mark - Delegate
-(void)printHello {
    NSLog(@"Hello");
}
@end

有B类具体实现委托方法,A类来声明和调用委托方法。在iOS一种常用的场景就是将视图代码中点击事件的回调方法委托到控制器中实现。

四.观察者模式(Observer)

在iOS中我们常用两种技术来实现观察者模式:NSNotificationKVO

NSNotification

NSNotification基于 Cocoa 的消息中心组件NSNotificationCenter实现。

观察者需要统一在消息中心注册,说明自己要观察哪些值的变化。

[[NSNotificationCenter defaultCenter] addObserver:self
                         selector:@selector(printName:)
                             name: @"messageName"
                           object:nil];

// 或者使用该方法来保证回调在主线程处理                        
[[NSNotificationCenter defaultCenter] addObserverForName:@"messageName"
                                                 object:nil
                                                 queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
                                                 // ...code
                                                 }]]

上面的函数表明把自身注册成 "messageName" 消息的观察者,当有消息时,会调用自己的printName方法。

消息发送者使用类似下面的函数发送消息:

[[NSNotificationCenter defaultCenter] postNotificationName:@"messageName"
                                    object:nil
                                  userInfo:nil];

KVO

KVO的实现依赖于 Objective-C 本身强大的 KVC(Key Value Coding) 特性(基于Runtime来实现),可以实现对于某个属性变化的动态监测。

示例代码如下:

// Book类
@interface Book : NSObject

@property NSString *name;
@property CGFloat price;

@end

// AClass类
@class Book;
@interface AClass : NSObject

@property (strong) Book *book;

@end

@implementation AClass

- (id)init:(Book *)theBook {
    if(self = [super init]){
        self.book = theBook;
        [self.book addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context{
    if([keyPath isEqual:@"price"]){
        NSLog(@"------price is changed------");
        NSLog(@"old price is %@",[change objectForKey:@"old"]);
        NSLog(@"new price is %@",[change objectForKey:@"new"]);
    }
}

- (void)dealloc{
    [self.book removeObserver:self forKeyPath:@"price"];
}
@end

// 使用 KVO
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Book *aBook = [Book new];
        aBook.price = 10.9;
        AClass * a = [[AClass alloc] init:aBook];
        aBook.price = 11; // 输出 price is changed
    }
    return 0;
}

results matching ""

    No results matching ""