工厂模式是一种快速创建大量对象的模式.简单易上手,今天我就谈一下我对工厂模式的理解.工厂模式的核心思想就是继承.子类继承父类的方法并且重写父类方法.下面我们就看一下实际中是如何使用工厂模式的.
*** 现在我们需要创建一百个对象,其中五十个是学生对象,五十是老师对象.两者都继承与Person类.现在我们需要在Person.h中声明一个创建方法.但是在Person.m中不做实现.
#import@interface Person : NSObject@property(nonatomic,strong)NSString *name;@end复制代码
然后我们需要在Student类中和Teacher类中对createNewObject方法进行方法的实现.当然了,Student类和Teacher类是继承于Person类的.
Student.中代码实现
#import "Person.h"@interface Student : Person@end复制代码
#import "Student.h"@end复制代码
Teacher中代码实现如下
#import "Person.h"@interface Teacher : Person@end复制代码
#import "Teacher.h"@implementation Teacher@end复制代码
下面就需要创建批量生产的初始化工厂PersonFactory.
PersonFactory.h中
#import@class Teacher;@class Student;@interface PersonFactory : NSObject//声明创建新对象的方法.+(Student *)createNewStudent;+(Teacher *)createNewTeacher;@end复制代码
PersonFactory.m中
#import "PersonFactory.h"#import "Student.h"#import "Teacher.h"@implementation PersonFactory//实现创建新对象的方法.+(Student *)createNewStudent{ Student *student = [[Student alloc]init]; student.name = @"栋哥"; return student; }+(Teacher *)createNewTeacher{ Teacher *teacher = [[Teacher alloc]init]; teacher.name = @"政哥"; return teacher; }@end复制代码
这里,我就使用ViewController调用一下createNewObject方法.然后我们就能批量生产带有特定name属性的学生对象和教师对象了.
#import "ViewController.h"#import "Teacher.h"#import "Student.h"#import "PersonFactory.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; Teacher *teacher = [PersonFactory createNewTeacher]; NSLog(@"%@",teacher.name); Student *student = [PersonFactory createNewStudent]; NSLog(@"%@",student.name); }@end复制代码
通过上面的方法,我们只能批量创建一些带有特殊属性的对象,如果现在我们需要把这些对象全部改变成另外的对象,我们改如何做呢? 这就需要我们再一步的细分我们的工厂.Person工厂中只做方法的声明,在Student工厂和Teacher中做出方法的实现.
PersonFactory.h中
#import@class Person;@interface PersonFactory : NSObject//只在.h中做方法的声明,在.m中不做方法的实现.+(Person *)createNewObject;@end复制代码
StudentFactory.m中
#import "StudentFactory.h"#import "Student.h"@implementation StudentFactory+(Person *)createNewObject{ Student *student = [[Student alloc]init]; student.name = @"栋哥"; return student;}@end复制代码
同样.TeacherFactory.m中.
#import "TeacherFactory.h"#import "Teacher.h"@implementation TeacherFactory+(Person *)createNewObject{ Teacher *teacher = [[Teacher alloc]init]; teacher.name = @"政哥"; return teacher; }@end复制代码
然后我们在ViewController中创建我们的两种对象.
#import "ViewController.h"#import "Person.h"#import "PersonFactory.h"#import "StudentFactory.h"#import "TeacherFactory.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; Person *teacher = [TeacherFactory createNewObject]; NSLog(@"%@",teacher.name); Person *student = [StudentFactory createNewObject]; NSLog(@"%@",student.name); }@end复制代码