iOS开发之设计模式 - 工厂模式

2019-03-28  本文已影响0人  JoeyM

由《大话设计模式 - 工厂模式》的OC和部分Swift的语言转义

工厂模式

继上一篇《代理模式》

工厂模式

例子: 一个学生学雷锋,去敬老院帮助老人, 有一天这个学生病倒了, 但是这个学生前一天答应王大爷,李阿姨,孙大伯,汪奶奶.... 要为他们做事情。 此大无畏事迹,传遍学校, 学生们纷纷表示,自己要代替这个学生去帮助老人。 (说的啥玩意, 你能懂么?哎, 不多BB, 代码说明一切。 哈哈哈)

OC

// 雷锋
@interface LeiFeng : NSObject
- (void)helpOthers:(NSString *)str;
@end

@implementation LeiFeng
- (void)helpOthers:(NSString *)str {
    NSLog(@"helpOthers %@", str);
}
@end

// 雷锋工厂
@interface IFactory : NSObject
- (instancetype)createLeiFeng;
@end

@implementation IFactory
- (instancetype)createLeiFeng {return nil;}
@end

// 学雷锋的大学生
@interface Undergraduate : LeiFeng
@end

@implementation Undergraduate
@end

// 学雷锋的大学生工厂
@interface UndergraduateFactory : IFactory
@end

@implementation UndergraduateFactory
- (instancetype)createLeiFeng {
    return (id)[Undergraduate new];
}
@end




// * 未来新增之后 方便用, 除修改主页面的逻辑之外, 任何类都不需要动用 *//
// 志愿者 (任何角色)
@interface Volunteer : LeiFeng
@end

@implementation Volunteer
@end

// 社区志愿者工厂
@interface VolunteerFactory : IFactory
@end

@implementation VolunteerFactory
- (instancetype)createLeiFeng {
    return (id)[Volunteer new];
}
@end

// 学习雷锋的男孩儿
@interface Boy : LeiFeng
@end

@implementation Boy
@end

// 学习雷锋的男孩工厂
@interface BoyFactory : IFactory
@end

@implementation BoyFactory
- (instancetype)createLeiFeng {
    return (id)[Boy new];
}
@end


@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 学生
    IFactory *factory = [UndergraduateFactory new];
    LeiFeng *student = (LeiFeng *)[factory createLeiFeng];
    [student helpOthers:@"Joey"];
    
    
    // 志愿者
    VolunteerFactory *volunteerF = [VolunteerFactory new];
    Volunteer *v1 = (Volunteer *)[volunteerF createLeiFeng];
    [v1 helpOthers:@"小F"];
    
    
    // boy
    BoyFactory *bf = [BoyFactory new];
    Boy *boy = (Boy *)[bf createLeiFeng];
    [boy helpOthers:@"Boy"];

.......
}


@end


简单工厂模式 VS. 工厂模式

未完待续..... (可能会停更一段时间,最近部门要求App进行组件化, 先研究那个去。。囧~)

上一篇下一篇

猜你喜欢

热点阅读