-
工厂模式
通过工厂模式将子类创建逻辑封装在一个方法或者说接口中,隐藏具体子类对象创建和初始化。
外部只需要告诉工厂需要创建什么类型的对象,工厂就可以创建出来。 -
应用,适用场景
父类拥有很多字类对象,但只有在程序运行时才能决定到底什么时候该创建哪一个子类对象。
父类(Person)
//
// Person.h
// LearnFactory
//
// Created by 印林泉 on 2017/3/1.
// Copyright © 2017年 yiq. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
//保证字类可以共享父类的成员变量
@protected
NSString *_name;
NSInteger _age;
}
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) void (^workBlock)(Person *person);
+ (instancetype)person;
- (void)dowork;
@end
//
// Person.m
// LearnFactory
//
// Created by 印林泉 on 2017/3/1.
// Copyright © 2017年 yiq. All rights reserved.
//
#import "Person.h"
@implementation Person
+ (instancetype)person {
return [[self alloc] init];
}
- (void)dowork {
if (self.workBlock) {
self.workBlock(self);
}
}
@end
子类(Student)
//
// Student.h
// LearnFactory
//
// Created by 印林泉 on 2017/3/1.
// Copyright © 2017年 yiq. All rights reserved.
//
#import "Person.h"
@interface Student : Person
- (void)readBookWithBookName:(NSString *)bookName;
@end
//
// Student.m
// LearnFactory
//
// Created by 印林泉 on 2017/3/1.
// Copyright © 2017年 yiq. All rights reserved.
//
#import "Student.h"
@implementation Student
- (void)readBookWithBookName:(NSString *)bookName {
NSLog(@"name %@, read book %@", _name, bookName);
}
@end
子类(Police)
//
// Police.h
// LearnFactory
//
// Created by 印林泉 on 2017/3/1.
// Copyright © 2017年 yiq. All rights reserved.
//
#import "Person.h"
@interface Police : Person
- (void)catchThiefWithName:(NSString *)thiefName;
@end
//
// Police.m
// LearnFactory
//
// Created by 印林泉 on 2017/3/1.
// Copyright © 2017年 yiq. All rights reserved.
//
#import "Police.h"
@implementation Police
- (void)catchThiefWithName:(NSString *)thiefName {
NSLog(@"catch thief %@", thiefName);
}
@end
应用
//
// ViewController.m
// LearnFactory
//
// Created by 印林泉 on 2017/3/1.
// Copyright © 2017年 yiq. All rights reserved.
//
#import "ViewController.h"
//#import "Student.h"
//#import "Police.h"
#import "PersonFactory.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//子类对象创建逻辑相似
//属性设置、方法调用,业务逻辑相似
//隐藏具体子类对象创建和初始化设置,工厂会在内部实现逻辑中自动给子类进行初始化设置
// Student *student = [Student person];
// [student setWorkBlock:^(Person *person) {
// Student *temp = (Student *)person;
// [temp readBookWithBookName:@"iOS"];
// }];
// [student dowork];
//
// Police *police = [Police person];
// [police setWorkBlock:^(Person *person) {
// Police *temp = (Police *)person;
// [temp catchThiefWithName:@"Tom"];
// }];
// [police dowork];
Person *person = [PersonFactory personWithTask:@"ReadBook"];
[person dowork];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
解决对象的创建时机。当设计的类无法完全预测创建对象的具体类型的时候。提供一种扩展的策略将类的实例化延迟到在子类进行。