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
分析
具体的制造者与具体的子类
关系伦理图