Objective-C可变子类模式?

wL_*_*wL_ 6 design-patterns objective-c mutable subclassing ios

在Objective-C中是否有用于实现可变/不可变对象类对的标准模式?我目前有类似以下内容,我根据此链接编写

不可变类:

@interface MyObject : NSObject <NSMutableCopying> {
    NSString *_value;
}

@property (nonatomic, readonly, strong) NSString *value;
- (instancetype)initWithValue:(NSString *)value;

@end

@implementation MyObject
@synthesize value = _value;
- (instancetype)initWithValue:(NSString *)value {
    self = [self init];
    if (self) {
        _value = value;
    }
    return self;
}


- (id)mutableCopyWithZone:(NSZone *)zone {
    return [[MyMutableObject allocWithZone:zone] initWithValue:self.value];
}

@end
Run Code Online (Sandbox Code Playgroud)

可变类:

@interface MyMutableObject : MyObject
@property (nonatomic, readwrite, strong) NSString *value;
@end


@implementation MyMutableObject
@dynamic value;

- (void)setValue:(NSString *)value {
    _value = value;
}

@end
Run Code Online (Sandbox Code Playgroud)

这有效,但它暴露了iVar.是否有更好的实施可以解决这种情况?

das*_*ght 4

您的解决方案遵循一个非常好的模式:可变类不会从其基类复制任何内容,并且公开附加功能而不存储任何附加状态。

这可行,但它暴露了 iVar。

由于实例变量是@protected默认的,因此暴露的变量_value仅对继承的类可见MyObject。这是一个很好的权衡,因为它可以帮助您避免数据重复,而无需公开公开用于存储对象状态的数据成员。