Objective C类继承与工厂方法 [英] Objective C class inheritance with factory methods
问题描述
我想从具有工厂方法的框架类继承。如何使工厂方法返回我继承的类类型的对象?我发现这篇有用的文章描述了类似的情况,但在他们的情况下,你可以控制超类。我怎么能写一个 UIImage
的子类, imageNamed:
会返回我的子类类型的对象? / p>
I would like to inherit from a framework class that has a factory method. How can I make the factory method return an object of my inherited class type? I found this useful article which describe a similar situation but in their case you have control over the superclass. How could I write, say, a subclass of UIImage
that imageNamed:
would return an object of my subclass type?
推荐答案
我想从具有工厂方法的框架类继承。如何让工厂方法返回我继承的类类型的对象?
I would like to inherit from a framework class that has a factory method. How can I make the factory method return an object of my inherited class type?
这就是应该 >必须这样做:
This is all you should have to do:
@interface MONImage : UIImage
@end
@implementation MONImage
@end
然后:
MONImage * image = [MONImage imageNamed:name];
我怎么能写一个UIImage的子类,imageNamed:会返回我的子类类型的对象吗?
How could I write, say, a subclass of UIImage that imageNamed: would return an object of my subclass type?
+ [UIImage imageNamed:]
的实现用这种方法写了子类。因此,您需要自己实现此方法。
+[UIImage imageNamed:]
's implementation wrote subclassers out of this approach. Consequently, you would need to implement this method yourself.
以下是应声明工厂方法的方式:
Here's how one should declare a factory method:
+ (instancetype)imageNamed:(NSString *)pName;
以及应如何实施它:
+ (instancetype)imageNamed:(NSString *)pName
{
MONImage * image = [[self alloc] initWithThisDesignatedInitializer:pName];
^^^^ NOTE: self, not a concrete class
...set up image...
return image;
}
但他们没有这样做 - + [UIImage imageNamed:]
编写子类并在编写时返回
。有时这是有充分理由的。有些方法应该具有'最终'语义。当您的方法可能返回多个类型时,通常会出现这种情况,如在类集群中。该语言不表达最终方法 - 但至少应该记录这种方法。 UIImage
MONImage * img = [MONImage imageNamed: PNAME];
but they did not do it that way -- +[UIImage imageNamed:]
wrote subclasses out and returns a UIImage
when you write MONImage * img = [MONImage imageNamed:pName];
. Sometimes that is done for a good reason. Some methods should have 'final' semantics. This often appears when your method may return multiple types, as in a class cluster. The language does not express 'final' methods -- but such a method should at least be documented.
所以来大约这个 UIImage
案例:
@interface MONImage : UIImage
+ (instancetype)imageNamed:(NSString *)pName;
@end
@implementation MONImage
+ (instancetype)imageNamed:(NSString *)pName
{
UIImage * source = [UIImage imageNamed:pName];
CGImageRef cgImage = source.CGImage;
if (cgImage)
return [[self alloc] initWithCGImage:cgImage];
// try it another way
return nil;
}
@end
请注意 UIImage
s和 CGImage
s是不可变的。这不应导致图像数据的深层复制。
Note that UIImage
s and CGImage
s are immutable. This should not result result in a deep copy of the image data.
这篇关于Objective C类继承与工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!