iOS設計模式 - 簡單工廠

weixin_33941350發表於2015-07-30

iOS設計模式 - 簡單工廠

 

原理圖

 

說明

1. 工廠類以及其例項化出來的子類都不是抽象類,所以稱之為簡單工廠(製造者與產品都是具體的實現類)

2. 簡單工廠靈活性較差,但其簡單直白的特性,適用於層級結構簡單的場景

 

原始碼

https://github.com/YouXianMing/iOS-Design-Patterns

//
//  DeviceCreator.h
//  FactoryPattern
//
//  Created by YouXianMing on 15/7/29.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "DeviceProtocol.h"
#import "iPhoneDevice.h"
#import "AndroidDevice.h"
#import "WindowsDevice.h"

typedef enum : NSUInteger {
    
    kAndroid,
    kiPhone,
    kWindows,
    
} DeviceType;

@interface DeviceCreator : NSObject

/**
 *  根據標籤建立手機
 *
 *  @param deviceType 手機標籤
 *
 *  @return 對應的手機
 */
+ (BaseDevice *)deviceCreatorWithDeviceType:(DeviceType)deviceType;

@end
//
//  DeviceCreator.m
//  FactoryPattern
//
//  Created by YouXianMing on 15/7/29.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

#import "DeviceCreator.h"
#import "BaseDevice.h"

@implementation DeviceCreator

+ (BaseDevice *)deviceCreatorWithDeviceType:(DeviceType)deviceType {

    if (deviceType == kiPhone) {
        
        return [iPhoneDevice new];
        
    } else if (deviceType == kAndroid) {
    
        return [AndroidDevice new];
        
    } else if (deviceType == kWindows) {
    
        return [WindowsDevice new];
        
    } else {
    
        return [BaseDevice new];
    }
}

@end
//
//  BaseDevice.h
//  FactoryPattern
//
//  Created by YouXianMing on 15/7/29.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "DeviceProtocol.h"

@interface BaseDevice : NSObject <DeviceProtocol>

@end
//
//  BaseDevice.m
//  FactoryPattern
//
//  Created by YouXianMing on 15/7/29.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

#import "BaseDevice.h"

@implementation BaseDevice

- (void)phoneCall {

    NSLog(@"... BaseDevice ...");
}

- (NSString *)systemInfomation {

    return @"BaseDevice";
}

@end

 

分析

具體的製造者與具體的子類

關係倫理圖

 

相關文章