zoukankan      html  css  js  c++  java
  • oc 工厂方法

    通过上例看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]);
    }
  • 相关阅读:
    Connected Graph
    Gerald and Giant Chess
    [NOI2009]诗人小G
    四边形不等式小结
    [NOI2007]货币兑换
    Cats Transport
    Cut the Sequence
    Fence
    The Battle of Chibi
    [Usaco2005 Dec]Cleaning Shifts
  • 原文地址:https://www.cnblogs.com/netcorner/p/4739160.html
Copyright © 2011-2022 走看看