温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Objective-C中如何使用模式

发布时间:2024-04-18 10:35:25 来源:亿速云 阅读:78 作者:小樊 栏目:移动开发

Objective-C 中使用设计模式与其他编程语言类似,可以通过创建类、接口、协议等来实现不同的设计模式。常见的设计模式包括单例模式、工厂模式、观察者模式、代理模式等。

以下是使用设计模式的示例:

  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

以上是一些常见的设计模式在 Objective-C 中的实现示例,开发者可以根据具体需求选择合适的设计模式来提高代码的可维护性和灵活性。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI