1. 程式人生 > >iOS 工廠模式

iOS 工廠模式

1. 概念

工廠模式用於建立某個類的子類例項的

要解決的問題:在其他地方,不確定要建立那個具體的子類的時候使用

2. 程式碼

1.Animal 動物類

#import <Foundation/Foundation.h>

// 動物類:作為父類
@interface Animal : NSObject
- (void)eat;
@end

#import "Animal.h"

@implementation Animal
- (void)eat {
    NSLog(@"Animal eating...");
}
@end

2. Dog 狗

#import "Animal.h"

@interface Dog : Animal
- (void)eat;
@end

#import "Dog.h"

@implementation Dog
- (void)eat {
    NSLog(@"Dog eating...");
}
@end

3. Cat 貓

#import "Animal.h"

@interface Cat : Animal
- (void)eat;
@end

#import "Cat.h"

@implementation Cat
- (void)eat {
    NSLog(@"Cat eating...");
}
@end

4.AnimalFactory 動物工廠

#import <Foundation/Foundation.h>
#import "Animal.h"
@interface AnimalFactory : NSObject

+ (Animal *)createAnimalWithName:(NSString *)name;

@end

#import "AnimalFactory.h"

@implementation AnimalFactory

// 工廠方法
+ (Animal *)createAnimalWithName:(NSString *)className {
    Class class = NSClassFromString(className);
    Animal *animal = [[class alloc] init];
    
    return animal;
}

@end

5. ViewController

#import "AnimalFactory.h"
#import "Animal.h"
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    Animal *animal = [AnimalFactory createAnimalWithName:@"Dog"];
    [animal eat];   // 列印 Dog eating...
}
@end