• oc37--类工厂方法


    //
    //  Person.h
    
    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject
    
    @property int age;
    @property double width;
    /*
     什么是类工厂方法:
     用于快速创建对象的类方法, 我们称之为类工厂方法
     类工厂方法中主要用于 给对象分配存储空间和初始化这块存储空间
     
     规范:
     1.一定是类方法 +
     2.方法名称以类的名称开头, 首字母小写
     3.一定有返回值, 返回值是id/instancetype
    */
    + (instancetype)person;
    
    + (instancetype)personWithAge:(int)age andWidth:(double)width;
    @end
    //
    //  Person.m
    
    
    #import "Person.h"
    
    @implementation Person
    
    /*
    + (instancetype)person
    {
        Person *p = [Person alloc];
        Person *p1 = [p init];
        return p1;
    }
     */
    + (instancetype)person
    {
        return [[Person alloc] init];
    }
    
    + (instancetype)personWithAge:(int)age andWidth:(double)width
    {
        Person *p = [[Person alloc] init];
        p.age = age;
        p.width = width;
        return p;
    }
    
    @end
    //
    //  main.m
    //  自定义类工厂方法
    
    #import <Foundation/Foundation.h>
    #import "Person.h"
    
    int main(int argc, const char * argv[]) {
    
        Person *p = [[Person alloc] init];
        Person *p12  = [Person person];
        p12.age = 30;
    
        Person *p1 = [Person personWithAge:30 andWidth:2.2];
        NSLog(@"age = %i", p1.age);
        /*
         自定义类工厂方法是苹果的一个规范(苹果就是这么写的), 一般情况下, 我们会给一个类提供自定义构造方法和自定义类工厂方法用于创建一个对象
         */
        
        
        /*
        NSString *s1 = [[NSString alloc] init];
        NSString *s2 = [NSString string];
        
        NSString *s3 = [[NSString alloc] initWithString: @"ss"];
        NSString *s4 = [NSString stringWithString:<#(NSString *)#>];
        
        NSArray *a1 = [[NSArray alloc] init];
        NSArray *a2 = [NSArray array];
        NSArray *a3 = [NSArray alloc] initWithObjects:{1,2,3}, nil
        NSArray *a4 = [NSArray arrayWithObjects:<#(id), ...#>, nil]
        */
        return 0;
    }
  • 相关阅读:
    Spring Boot 使用actuator监控与管理
    Spring Boot入门
    mysql中update语句的锁
    LinkedList深入学习
    23种设计模式学习之享元模式
    23种设计模式学习之桥接模式
    23种设计模式学习之外观模式
    23种设计模式学习之代理模式
    23种设计模式学习之装饰者模式
    23种设计模式学习之适配器模式
  • 原文地址:https://www.cnblogs.com/yaowen/p/7417848.html
Copyright © 2020-2023  润新知