首页 > 其他 > 详细

oc 工厂方法

时间:2015-08-18 13:58:51      阅读:271      评论:0      收藏:0      [点我收藏+]

通过上例看oc创建实例有点麻烦,oc里面可以创建工厂方法可以让这个操作更简单一些(其实就是c#或者java里面的静态方法)。

新建一个“Cocoa Touch Class”文件,命名为People

People.h 写入

@interface People : NSObject{
    int _age;
    NSString* _name;
}
-(int)getAge;
-(NSString*)getName;
+(People*)peopleWithAge:(int)age andName:(NSString*)name;//+就是工厂方法,即表示静态方法
-(id)initWidthAge:(int)age andName:(NSString*)name;//id指的是任意类型 @end

People.m写入

@implementation People
-(int)getAge{
    return _age;
}
-(NSString*)getName{
    return _name;
}
+(People*)peopleWithAge:(int)age andName:(NSString*)name{
    return [[People alloc] initWidthAge:age andName:name];
}

- (instancetype)initWidthAge:(int)age andName:(NSString *)name
{
    self = [super init];
    if (self) {
        _age=age;
        _name=name;
    }
    return self;
}

@end

主程序:

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "People.h"

int main(int argc, char * argv[]) {
    People *p=[People peopleWithAge:30 andName:@"netcorner"];
    NSLog(@"p.age %d,p.name %@",[p getAge], [p getName]);
}

 

oc 工厂方法

原文:http://www.cnblogs.com/netcorner/p/4739160.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!