
@class Engine, Wheel, Car;
//Visitor
//There is no overloading by parameter type in Objective-C:
//every visit has its own selector, and the element itself
//picks the right one in accept
@protocol CarVisitor <NSObject>
- (void)visitEngine:(Engine *)engine;
- (void)visitWheel:(Wheel *)wheel;
- (void)visitCar:(Car *)car;
@end
@protocol Element <NSObject>
- (void)accept:(id<CarVisitor>)v;
@end
//ConcreteElement
@interface Engine : NSObject <Element>
@end
@implementation Engine
- (void)accept:(id<CarVisitor>)v {
[v visitEngine:self];
}
@end
//ConcreteElement
@interface Wheel : NSObject <Element>
@property (nonatomic, readonly) NSInteger number;
- (instancetype)initWithNumber:(NSInteger)number;
@end
@implementation Wheel
- (instancetype)initWithNumber:(NSInteger)number {
self = [super init];
if (self) {
_number = number;
}
return self;
}
- (void)accept:(id<CarVisitor>)v {
[v visitWheel:self];
}
@end
//ConcreteElement
@interface Car : NSObject <Element>
@property (nonatomic, strong, readonly) NSArray<id<Element>> *items;
@end
@implementation Car
- (instancetype)init {
self = [super init];
if (self) {
_items = @[[[Engine alloc] init],
[[Wheel alloc] initWithNumber:1],
[[Wheel alloc] initWithNumber:2],
[[Wheel alloc] initWithNumber:3],
[[Wheel alloc] initWithNumber:4]];
}
return self;
}
- (void)accept:(id<CarVisitor>)v {
for (id<Element> e in self.items) {
[e accept:v];
}
[v visitCar:self];
}
@end
//ConcreteVisitor
@interface TestCarVisitor : NSObject <CarVisitor>
@end
@implementation TestCarVisitor
- (void)visitEngine:(Engine *)engine {
NSLog(@"test engine");
}
- (void)visitWheel:(Wheel *)wheel {
NSLog(@"test wheel #%ld", (long)wheel.number);
}
- (void)visitCar:(Car *)car {
NSLog(@"test car");
}
@end
//ConcreteVisitor
@interface RepairCarVisitor : NSObject <CarVisitor>
@end
@implementation RepairCarVisitor
- (void)visitEngine:(Engine *)engine {
NSLog(@"repair engine");
}
- (void)visitWheel:(Wheel *)wheel {
NSLog(@"repair wheel #%ld", (long)wheel.number);
}
- (void)visitCar:(Car *)car {
NSLog(@"repair car");
}
@end
//Client
Car *car = [[Car alloc] init];
TestCarVisitor *v1 = [[TestCarVisitor alloc] init];
RepairCarVisitor *v2 = [[RepairCarVisitor alloc] init];
[car accept:v1];
[car accept:v2];
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.Read more问题。一份文档由段落、图片和表格组成。程序必须能导出文档、统计字数并检查拼写。如果把每个操作都作为方法加到每一种组成部分上,每增加一个操作,这些部分的类就膨胀一次。而且一个操作的代码还会分散在许多类中。 思路。每个操作都变成一个单独的对象,称为访问者。访问者为每一种元素各准备一个方法。每个元素有一个方法,它接收一个访问者,并调用访问者中对应自己种类的方法。这样,每一对元素和操作都会运行正确的代码,无需检查类型。要增加一个新操作,只需编写一个新的访问者;元素类保持不变。 如何阅读示例。元素分为几种。每个具体访问者是一个操作,为每一种元素各有一个单独的方法。客户端代码把访问者交给元素,每个元素再把它送到对应自己种类的方法。在大多数示例中,一个元素包含其他元素,并把访问者交给自己的每个组成部分。随后两个访问者依次经过同样的这些部分,各自执行自己的操作。在某些语言中,元素是带有类型标签的普通数据,访问者是一个函数,为每一种元素各有一个版本。 何时使用。当元素类的集合保持稳定、而针对它们的新操作经常出现时,使用访问者模式。经常增加新的元素种类时不要使用它:每增加一种元素,每个访问者都需要一个新方法。 常见错误。在一个通用的访问者方法内部用条件判断检查元素的类型。这样,新的元素种类会在毫无警告的情况下被遗漏。应为每一种元素提供它自己的方法。 |