溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Objective-C中如何使用模式

發(fā)布時(shí)間:2024-04-18 10:35:25 來源:億速云 閱讀:80 作者:小樊 欄目:移動開發(fā)

Objective-C 中使用設(shè)計(jì)模式與其他編程語言類似,可以通過創(chuàng)建類、接口、協(xié)議等來實(shí)現(xiàn)不同的設(shè)計(jì)模式。常見的設(shè)計(jì)模式包括單例模式、工廠模式、觀察者模式、代理模式等。

以下是使用設(shè)計(jì)模式的示例:

  1. 單例模式:
@interface Singleton : NSObject
+ (instancetype)sharedInstance;
@end

@implementation Singleton

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

@end
  1. 工廠模式:
@interface ShapeFactory : NSObject
+ (id)createShapeWithType:(NSString *)type;
@end

@implementation ShapeFactory

+ (id)createShapeWithType:(NSString *)type {
    if ([type isEqualToString:@"Circle"]) {
        return [[Circle alloc] init];
    } else if ([type isEqualToString:@"Square"]) {
        return [[Square alloc] init];
    } else {
        return nil;
    }
}

@end
  1. 觀察者模式:
@protocol ObserverProtocol <NSObject>
- (void)update;
@end

@interface Subject : NSObject
@property (nonatomic, strong) NSMutableArray<id<ObserverProtocol>> *observers;
- (void)addObserver:(id<ObserverProtocol>)observer;
- (void)notifyObservers;
@end

@implementation Subject

- (instancetype)init {
    self = [super init];
    if (self) {
        _observers = [NSMutableArray array];
    }
    return self;
}

- (void)addObserver:(id<ObserverProtocol>)observer {
    [self.observers addObject:observer];
}

- (void)notifyObservers {
    for (id<ObserverProtocol> observer in self.observers) {
        [observer update];
    }
}

@end
  1. 代理模式:
@protocol PrinterDelegate <NSObject>
- (void)printMessage:(NSString *)message;
@end

@interface Printer : NSObject
@property (nonatomic, weak) id<PrinterDelegate> delegate;
- (void)print;
@end

@implementation Printer

- (void)print {
    [self.delegate printMessage:@"Hello, World!"];
}

@end

以上是一些常見的設(shè)計(jì)模式在 Objective-C 中的實(shí)現(xiàn)示例,開發(fā)者可以根據(jù)具體需求選擇合適的設(shè)計(jì)模式來提高代碼的可維護(hù)性和靈活性。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI