类方法用来创建对象的方法就是工厂方法

1、无参工厂方法

创建对象,并给属性一个默认值。


//无参工厂方法实现
+(Student*)student{
    return [[Student alloc]init];
}

2、有参工厂方法

  2.1.要依赖有参的初始化方法 -(id)initWithAge:(int)age;

    2.2.创建对象,并给属性一个指定的值   

//有参工厂方法实现
+(Student*)studentWithAge:(int)age andSex:(char)sex andSalary:(double)salary{
    return  [[Student alloc]initWithAge:age andSex:sex andSalary:salary];
}

规范:
工厂方法的方法名一定以类名开头,注意去除了前缀,首字母 要小写
工厂方法,不但使用自定义类,官方的类也遵守这个规范

 类Student.h

Objective-C 工厂方法

 

 

Objective-C 工厂方法

 

 

Objective-C 工厂方法

 

 

Objective-C 工厂方法

相关文章:

  • 2022-12-23
  • 2021-05-31
  • 2021-09-06
  • 2021-11-07
  • 2021-06-01
  • 2021-08-15
  • 2021-11-14
  • 2021-06-11
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-13
  • 2021-11-19
相关资源
相似解决方案