工厂模式、抽象工厂模式

2018-02-06  本文已影响18人  Carson_Zhu

工厂模式

工厂模式就是定义创建对象的接口,让子类决定实例化哪一个类。这样,类的实例化就推迟到了子类

特点
应用

定义一个衣服的基类,暴露一个初始化接口。

@interface Cloth : NSObject
+ (instancetype)create;
@end
@implementation Cloth
+ (instancetype)create {
    return [[self alloc] init];
}
@end

衬衣Shirt类继承Cloth,毛衣Sweater类也继承Cloth,他们都可以用create进行初始化。

Shirt *aShirt = [Shirt create];
Sweater *aSweater = [Sweater create];
解决问题

用工厂的方式实现,让其子类决定在运行期具体实例化的对象,使得类的调用者能够专注于接口。而不需要访问具体的实现类。


抽象工厂模式

抽象工厂提供一个固定的接口,用于创建一系列有关联或相依存的对象,而不必指定其具体类或其创建的细节。客户端与从工厂得到的具体对象之间没有耦合。

抽象工厂与工厂模式的区别
应用
@interface Cloth : NSObject
+ (instancetype)create;
@end
@implementation Cloth
+ (instancetype)create {
    return [[self alloc] init];
}
@end

衣服工厂

@interface ClothFactory : NSObject
+ (Cloth *)createShirt;
+ (Cloth *)createSweater;
@end
@implementation ClothFactory
+ (Cloth *)createShirt {
    return nil;
}
+ (Cloth *)createSweater {
    return nil;
}
@end

AdidasShirt继承于ClothAdidasSweater继承于Cloth,用衣服工厂生产Adidas系列ShirtSweater

@implementation Adidas
+ (Cloth *)createShirt {
    return [AdidasShirt create];
}
+ (Cloth *)createSweater {
    return [AdidasSweater create];
}
@end

NikeShirt继承于ClothNikeSweater继承于Cloth,用衣服工厂生产Nike系列ShirtSweater

@implementation Nike
+ (Cloth *)createShirt {
    return [NikeShirt create];
}
+ (Cloth *)createSweater {
    return [NikeSweater create];
}
@end

类簇

类簇是抽象工厂的一种形式,它将若干相关的私有具体工厂子类集合到一个公有的抽象超类之下。

应用
- (NSNumber *)initWithChar:(char)value NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithUnsignedChar:(unsigned char)value NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithShort:(short)value NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithUnsignedShort:(unsigned short)value NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithInt:(int)value NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithUnsignedInt:(unsigned int)value NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithLong:(long)value NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithUnsignedLong:(unsigned long)value NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithLongLong:(long long)value NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithUnsignedLongLong:(unsigned long long)value NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithFloat:(float)value NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithDouble:(double)value NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithBool:(BOOL)value NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithInteger:(NSInteger)value API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) NS_DESIGNATED_INITIALIZER;
- (NSNumber *)initWithUnsignedInteger:(NSUInteger)value API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) NS_DESIGNATED_INITIALIZER;
上一篇 下一篇

猜你喜欢

热点阅读