objective-C : 工厂方法

来源:互联网 发布:广州市软件创新人才 编辑:程序博客网 时间:2024/05/22 13:46

#import <Foundation/Foundation.h>


@interface people : NSObject{

    NSString* _name;

    int _age;

}

//下面创建工厂方法(为了更快捷的创建类的实例而存在),注意:工厂方法以 “+”开头

+(people*)peopleWithAge:(int)age andName:(NSString*)name;

//一般情况下创建一个类的实例要进行初始化例如: people* p=[people alloc]init];

//所以在这里也要声明一个初始化方法 :(id)开头

-(id)initWithAge:(int)age andName:(NSString*)name;


-(int)getAge;

-(NSString*)getName;//这两个方法用于输出传入过来的_name _age参数

@end



//实现类的方法

#import "people.h"

@implementation people

+(people*)peopleWithAge:(int)age andName:(NSString *)name{

    return [[peoplealloc]initWithAge:ageandName:name];}

- (instancetype)initWithAge:(int)age andName:(NSString *)name

self = [superinit];

    if (self) {

        _age=age;

        _name=name;//self用来指明对象是当前方法的接收者(本例中people是这个初始化方法的接收者)

    }

    return self;

}

-(NSString*)getName{

    return _name;}

-(int)getAge{

    return _age;}

@end


//  2 在主调函数中 创建一个类的实例 并赋值 输出

#import <Foundation/Foundation.h>

#import "people.h"

int main(int argc,constchar * argv[]) {

    @autoreleasepool {

        

        people *p=[peoplepeopleWithAge:55 andName:@"习近平"];

//定义类的实例的时候就可以直接将值传给参数,然后通过get方法进行显示

        NSLog(@"\n\n she's name is %@ , %d years old \n  ",[p getName],[p getAge]);

        

    }

    return 0;

}





 
1 0
原创粉丝点击