在Objective-C环境中使用工厂方法的目的是什么? [英] What is the purpose of using a factory method in objective-c context?

查看:100
本文介绍了在Objective-C环境中使用工厂方法的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C环境中使用工厂方法的目的是什么?

What is the purpose of use of a factory method in objective-c context?

我对在Objective-C中使用工厂方法有些困惑?这样做的用处是什么?

I am a bit confused about the use of factory methods in objective-c? What is the usefulness of doing so?

在Objective-C中使用工厂方法的例子是什么?

What is an example of using factory method in objective-c?

有点困惑.任何解释都会有所帮助!

A bit confused. Any explanation would help!

推荐答案

Objective-C没有其他编程语言中可用的构造方法.工厂方法本质上是Objective C的构造方法.它们使您可以为对象分配内存并初始化值.

Objective-C does not have constructor methods that are available in other programming languages. Factory methods are essentially Objective C's constructor methods. They allow you to allocate memory for your object and initialize the values.

在您的课程中,添加具有以下模式的方法:

In your class, add methods with this pattern:

//Please follow Obj C naming conventions and name all init 
//methods "initWith" then desc
-(id)initWithString:(NSString*)str {
    if(self = [super init]) {
        _someProperty = str;
        _someOtherProperty = 0;
    } return self;
}

//Please follow Obj C naming conventions and name all factory 
//methods "myClassWith" then desc
+(instancetype)someClassWithString:(NSString*)str {
    return [[self alloc] initWithString: str];
}

//Pretty much every factory method should have a matching init method, and 
//only one init method should actually do the if(self = [super init] { /*do
//stuff*/ } return self;, the other init methods should call this one in some
//form or fashion

然后在主要方面,您可以执行以下操作:

Then in main, you can do:

SomeClass *myVariableName = [SomeClass someClassWithString: 
    @"Init with me please"];

它使您不必这样做:

SomeClass *myVariableName = [[SomeClass alloc] initWithString: 
    @"Init with me please"];

或者这个:

SomeClass *myVariableName = [[SomeClass alloc] init];
[myVariableName mySetterMethod: @"Init with me please"];
[myVariableName setThatOtherProperty: 0];

这篇关于在Objective-C环境中使用工厂方法的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆