您好,登錄后才能下訂單哦!
Objective-C 中使用設(shè)計(jì)模式與其他編程語言類似,可以通過創(chuàng)建類、接口、協(xié)議等來實(shí)現(xiàn)不同的設(shè)計(jì)模式。常見的設(shè)計(jì)模式包括單例模式、工廠模式、觀察者模式、代理模式等。
以下是使用設(shè)計(jì)模式的示例:
@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
@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
@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
@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ù)性和靈活性。
免責(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)容。