模拟工厂方法

使用属性、初始化方法(无参、有参)、工厂方法(无参、有参)的概念重构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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值