面试题答案
一键面试组合模式基本结构组成部分
- Component(抽象构件):定义了组合中对象的共有接口,既可以是叶子节点(如员工)也可以是组合节点(如部门)。
- Leaf(叶子构件):是组合中的叶子节点对象,没有子节点,实现Component定义的接口。
- Composite(组合构件):有子节点的对象,通常包含一个集合用于存储子Component,实现Component接口中与子节点相关的操作。
Objective - C代码实现公司组织架构场景
- 定义抽象构件
Employee
类
#import <Foundation/Foundation.h>
@interface Employee : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger salary;
- (instancetype)initWithName:(NSString *)name salary:(NSInteger)salary;
- (void)printDetails;
@end
@implementation Employee
- (instancetype)initWithName:(NSString *)name salary:(NSInteger)salary {
self = [super init];
if (self) {
_name = name;
_salary = salary;
}
return self;
}
- (void)printDetails {
NSLog(@"Employee: %@, Salary: %ld", self.name, (long)self.salary);
}
@end
- 定义组合构件
Department
类
#import "Employee.h"
@interface Department : Employee
@property (nonatomic, strong) NSMutableArray<Employee *> *subEmployees;
- (instancetype)initWithName:(NSString *)name;
- (void)addEmployee:(Employee *)employee;
- (void)removeEmployee:(Employee *)employee;
- (void)printDetails;
@end
@implementation Department
- (instancetype)initWithName:(NSString *)name {
self = [super initWithName:name salary:0];
if (self) {
_subEmployees = [NSMutableArray array];
}
return self;
}
- (void)addEmployee:(Employee *)employee {
[self.subEmployees addObject:employee];
}
- (void)removeEmployee:(Employee *)employee {
[self.subEmployees removeObject:employee];
}
- (void)printDetails {
NSLog(@"Department: %@", self.name);
for (Employee *employee in self.subEmployees) {
[employee printDetails];
}
}
@end
- 使用示例
#import <Foundation/Foundation.h>
#import "Department.h"
#import "Employee.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Department *company = [[Department alloc] initWithName:@"My Company"];
Department *engineering = [[Department alloc] initWithName:@"Engineering"];
[company addEmployee:engineering];
Employee *engineer1 = [[Employee alloc] initWithName:@"John" salary:5000];
[engineering addEmployee:engineer1];
Employee *engineer2 = [[Employee alloc] initWithName:@"Jane" salary:5500];
[engineering addEmployee:engineer2];
Department *sales = [[Department alloc] initWithName:@"Sales"];
[company addEmployee:sales];
Employee *salesman1 = [[Employee alloc] initWithName:@"Bob" salary:4500];
[sales addEmployee:salesman1];
[company printDetails];
}
return 0;
}
以上代码中,Employee
类作为抽象构件,Department
类继承自 Employee
并作为组合构件,叶子构件是普通的 Employee
实例。通过组合这些对象构建出公司的组织架构,并通过调用 printDetails
方法展示结构信息。