概念异同
- 装饰器模式:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰器模式相比生成子类更为灵活。它把对象的核心职责和装饰功能分离,通过组合的方式而非继承来实现功能扩展。
- 代理模式:为其他对象提供一种代理以控制对这个对象的访问。代理对象起到中介作用,代替真实对象完成一些操作,比如延迟加载、权限控制等。
- 相同点:都涉及到对对象功能的增强或扩展。
- 不同点:装饰器模式主要侧重于在运行时动态添加功能;代理模式重点在于控制对对象的访问,强调代理对象对真实对象的代理关系;
适用场景异同
- 装饰器模式:适用于需要在运行时为对象动态添加功能的场景,例如给图片视图动态添加水印、滤镜等功能。
- 策略模式:当有多种算法相似的行为,并且需要根据不同情况选择不同算法时使用,比如支付方式有多种,根据用户选择调用不同支付算法。
- 相同点:在一些需要灵活处理对象行为的场景可能都适用。
- 不同点:装饰器模式更关注对单一对象功能的动态扩展;策略模式更关注算法的选择和替换。
实现方式异同
- 装饰器模式:在Objective-C中,通常通过定义一个抽象装饰类,其持有被装饰对象的引用,具体装饰类继承抽象装饰类并实现特定的装饰功能。例如:
// 抽象组件
@interface Component : NSObject
- (void)operation;
@end
// 具体组件
@interface ConcreteComponent : Component
- (void)operation {
NSLog(@"ConcreteComponent operation");
}
@end
// 抽象装饰类
@interface Decorator : Component
@property (nonatomic, strong) Component *component;
- (instancetype)initWithComponent:(Component *)component;
@end
@implementation Decorator
- (instancetype)initWithComponent:(Component *)component {
self = [super init];
if (self) {
_component = component;
}
return self;
}
- (void)operation {
[self.component operation];
}
@end
// 具体装饰类
@interface ConcreteDecoratorA : Decorator
- (void)operation {
[super operation];
NSLog(@"ConcreteDecoratorA added behavior");
}
@end
- 代理模式:在Objective-C中,代理模式通常通过协议(protocol)来实现。代理对象遵循特定协议,实现协议方法来代理真实对象的操作。例如:
// 定义协议
@protocol RealObjectProtocol <NSObject>
- (void)doSomething;
@end
// 真实对象
@interface RealObject : NSObject <RealObjectProtocol>
- (void)doSomething {
NSLog(@"RealObject doSomething");
}
@end
// 代理对象
@interface ProxyObject : NSObject <RealObjectProtocol>
@property (nonatomic, strong) RealObject *realObject;
- (instancetype)initWithRealObject:(RealObject *)realObject;
@end
@implementation ProxyObject
- (instancetype)initWithRealObject:(RealObject *)realObject {
self = [super init];
if (self) {
_realObject = realObject;
}
return self;
}
- (void)doSomething {
// 代理前操作
[self.realObject doSomething];
// 代理后操作
}
@end
- 相同点:都涉及对象之间的组合关系。
- 不同点:装饰器模式主要通过继承抽象装饰类并组合被装饰对象来实现;代理模式通过遵循协议并持有真实对象引用来实现。
装饰器模式类数量增加的优化
- 使用类别(Category):在Objective-C中,可以使用类别为现有类添加方法,实现类似装饰器的功能,且不会增加类的数量。例如:
@interface UIView (Watermark)
- (void)addWatermark:(NSString *)watermark;
@end
@implementation UIView (Watermark)
- (void)addWatermark:(NSString *)watermark {
// 添加水印逻辑
}
@end
- 使用协议扩展(Protocol Extension):定义一个协议,然后通过协议扩展为遵循该协议的类添加默认实现,达到功能扩展的目的,同时避免类数量增加。例如:
@protocol ViewEnhanceProtocol <NSObject>
@optional
- (void)addSpecialEffect;
@end
@interface UIView () <ViewEnhanceProtocol>
@end
@implementation UIView (ViewEnhanceProtocol)
- (void)addSpecialEffect {
// 添加特效逻辑
}
@end