MST

星途 面试题库

面试题:Objective-C中组合模式的基本结构及实现思路

请阐述在Objective-C里组合模式的基本结构组成部分,比如有哪些角色,并简要说明如何使用Objective-C代码实现一个简单的组合模式场景,例如一个公司组织架构,部门下有员工和子部门。
38.1万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

组合模式基本结构组成部分

  1. Component(抽象构件):定义了组合中对象的共有接口,既可以是叶子节点(如员工)也可以是组合节点(如部门)。
  2. Leaf(叶子构件):是组合中的叶子节点对象,没有子节点,实现Component定义的接口。
  3. Composite(组合构件):有子节点的对象,通常包含一个集合用于存储子Component,实现Component接口中与子节点相关的操作。

Objective - C代码实现公司组织架构场景

  1. 定义抽象构件 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
  1. 定义组合构件 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
  1. 使用示例
#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 方法展示结构信息。