模式 / 创建型模式
image

//abstract product A
@protocol IProductA <NSObject>
- (void)testA;
@end

//abstract product B
@protocol IProductB <NSObject>
- (void)testB;
@end

//abstract factory
@protocol IFactory <NSObject>
- (id<IProductA>)createA;
- (id<IProductB>)createB;
@end

//concrete product A1
@interface ProductA1 : NSObject <IProductA>
@end

@implementation ProductA1
- (void)testA {
    NSLog(@"test A1");
}
@end

//concrete product A2
@interface ProductA2 : NSObject <IProductA>
@end

@implementation ProductA2
- (void)testA {
    NSLog(@"test A2");
}
@end

//concrete product B1
@interface ProductB1 : NSObject <IProductB>
@end

@implementation ProductB1
- (void)testB {
    NSLog(@"test B1");
}
@end

//concrete product B2
@interface ProductB2 : NSObject <IProductB>
@end

@implementation ProductB2
- (void)testB {
    NSLog(@"test B2");
}
@end

//concrete factory 1
@interface Factory1 : NSObject <IFactory>
@end

@implementation Factory1

- (id<IProductA>)createA {
    return [[ProductA1 allocinit];
}

- (id<IProductB>)createB {
    return [[ProductB1 allocinit];
}
@end

//concrete factory 2
@interface Factory2 : NSObject <IFactory>
@end

@implementation Factory2

- (id<IProductA>)createA {
    return [[ProductA2 allocinit];
}

- (id<IProductB>)createB {
    return [[ProductB2 allocinit];
}
@end

//client code
void testFactory(id<IFactory> factory) {
    id<IProductA> productA = [factory createA];
    id<IProductB> productB = [factory createB];
    [productA testA];
    [productB testB];
}

testFactory([[Factory1 allocinit]);
//printed: test A1
//         test B1
testFactory([[Factory2 allocinit]);
//printed: test A2
//         test B2


Provides an interface for creating families of objects whose interfaces are known but concrete classes are not.