您的位置:首页 > 其它

模拟工厂方法

2016-04-09 10:33 351 查看
使用属性、初始化方法(无参、有参)、工厂方法(无参、有参)的概念重构Student类,在类中包含以下实例变量int age、char gender、double salary信息,定义一个方法printInfo输出所有实例变量的值,在主函数中对Student类的对象进行赋值并输出。

//
//  Student.h
//  Oc-Day1
//
//  Created by spare on 16/4/9.
//  Copyright © 2016年 spare. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Student : NSObject

@property int age;
@property char gender;
@property double salary;

//在Student类中添加两个方法,一个是无参初始化方法,另一个是有参初始化方法。
-(id)init;
-(id)initWithAge:(int)age andGender:(char)gender andSalary:(double)salary;
//用于对工厂方法的声明,需要注意的是工厂方法以加号“+”开头,而实例方法则以减号“-”开头。
//工厂方法本质上是类的静态方法,其调用是通过类名直接调用的,与实例方法不同,实例方法是通过对象来调用的。
+(id)creat;
+(id)creatWithAge:(int)age andGender:(char)gender andSalary:(double)salary;

-(void) printInfo;

@end


//
//  Student.m
//  Oc-Day1
//
//  Created by spare on 16/4/9.
//  Copyright © 2016年 spare. All rights reserved.
//

#import "Student.h"

@implementation Student

-(id)init{
//是首先发消息[super init]调用基类中的init方法获得self值
if(self=[super init]){
_age=33;
_gender='M';
_salary=20000;
}
return self;
}

-(id)initWithAge:(int)age andGender:(char)gender andSalary:(double)salary{
if (self=[super init]) {
_age=age;
_salary=salary;
_gender=gender;
}
return self;
}

+(id)creat{
Student *stu=[[Student alloc]init];
return stu;
}

+(id)creatWithAge:(int)age andGender:(char)gender andSalary:(double)salary{
Student *stu=[[Student alloc]initWithAge:age andGender:gender andSalary:salary];
return stu;
}

-(void)printInfo{
NSLog(@"age=%d,gender=%c,salary=%lf",_age,_gender,_salary);
}

@end


//
//  main.m
//  Oc-Day1
//
//  Created by spare on 16/4/9.
//  Copyright © 2016年 spare. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Student.h"

int main(int argc, const char * argv[]) {
@autoreleasepool {

Student *stu=[[Student alloc]init];
[stu printInfo];
Student *stu1=[[Student alloc]initWithAge:20 andGender:'M' andSalary:3000];
[stu1 printInfo];

Student *stu2=[[Student alloc]initWithAge:30 andGender:'M' andSalary:20000];

[stu2 printInfo];
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: