工厂模式(1)简单工厂模式

设计模式系列文章


1、概念描述

简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。

2、场景举例


马戏团有dog和duck两只动物,团长向驯兽师下指令,指定哪一只动物进行表演

3、代码实现


各个类的说明:
  SIMAnimalProtocol:定义协议
  SIMAnimalFactory:工厂类(驯兽师)
  SIMAnimal:动物父类
  SIMAnimalDog:小狗
  SIMAnimalDuck:小鸭
  SIMViewController:控制器(团长)
SIMAnimalProtocol:
//具体代码:
#import 

@protocol SIMAnimalProtocol 

- (void)animalWalk; //动物走
- (void)animalBark; //动物叫

@end
SIMAnimal.h
#import 
#import "SIMAnimalProtocol.h"

@interface SIMAnimal : NSObject

@property (strong, nonatomic) NSString *walkStr;
@property (strong, nonatomic) NSString *barkStr;

@end
SIMAnimal.m
#import "SIMAnimal.h"

@implementation SIMAnimal

- (void)animalWalk {
    self.walkStr = @"我们走";
}

- (void)animalBark {
    self.barkStr = @"叫一声";
}

@end
SIMAnimalDog.h
#import 
#import "SIMAnimal.h"

@interface SIMAnimalDog : SIMAnimal

@end
SIMAnimalDog.m
#import "SIMAnimalDog.h"

@implementation SIMAnimalDog

- (void)animalWalk {
    [super animalWalk];
    NSLog(@"旺财,%@", self.walkStr);
}

- (void)animalBark {
    [super animalBark];
    NSLog(@"旺财,%@", self.barkStr);
}

@end
SIMAnimalDuck.h
#import 
#import "SIMAnimal.h"

@interface SIMAnimalDuck : SIMAnimal

@end
SIMAnimalDuck.m
#import "SIMAnimalDuck.h"

@implementation SIMAnimalDuck

- (void)animalWalk {
    [super animalWalk];
    NSLog(@"duck,%@", self.walkStr);
}

- (void)animalBark {
    [super animalBark];
    NSLog(@"duck,%@", self.barkStr);
}

@end
SIMAnimalFactory.h
#import 
#import "SIMAnimal.h"
#import "SIMAnimalDog.h"
#import "SIMAnimalDuck.h"

typedef NS_ENUM(NSUInteger, AnimalType) {
    AnimalType_dog,
    AnimalType_duck,
};

@interface SIMAnimalFactory : NSObject

+ (SIMAnimal *)assignAnimalWithType:(AnimalType)animalType;

@end
SIMAnimalFactory.m
#import "SIMAnimalFactory.h"

@implementation SIMAnimalFactory

+ (SIMAnimal *)assignAnimalWithType:(AnimalType)animalType {
    SIMAnimal *animal;
    switch (animalType) {
        case AnimalType_dog:
            animal = [[SIMAnimalDog alloc] init];
            break;
            
        case AnimalType_duck:
            animal = [[SIMAnimalDuck alloc] init];
            break;
            
        default:
            break;
    }
    return animal;
}

@end
SIMViewController.h
#import 

@interface SIMViewController : UIViewController

@end
SIMViewController.m
#import "SIMViewController.h"
#import "SIMAnimalFactory.h"

@interface SIMViewController ()

@end

@implementation SIMViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self dogShow];
    [self duckShow];
}

- (void)dogShow {
    SIMAnimal *animal = [SIMAnimalFactory assignAnimalWithType:AnimalType_dog];
    [animal animalBark];
    [animal animalWalk];
}

- (void)duckShow {
    SIMAnimal *animal = [SIMAnimalFactory assignAnimalWithType:AnimalType_duck];
    [animal animalBark];
    [animal animalWalk];
}

@end
打印结果:
工厂模式(1)简单工厂模式_第1张图片
简单工厂模式.png

你可能感兴趣的:(工厂模式(1)简单工厂模式)