简单工厂模式
2019-10-08 本文已影响0人
CaptainRoy
- 协议 Product.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol Product <NSObject>
-(void)productMethod;
@end
NS_ASSUME_NONNULL_END
- ProductA
#import <Foundation/Foundation.h>
#import "Product.h"
NS_ASSUME_NONNULL_BEGIN
@interface ProductA : NSObject<Product>
@end
NS_ASSUME_NONNULL_END
#import "ProductA.h"
@implementation ProductA
-(void)productMethod
{
}
@end
- ProductB
#import <Foundation/Foundation.h>
#import "Product.h"
NS_ASSUME_NONNULL_BEGIN
@interface ProductB : NSObject<Product>
@end
NS_ASSUME_NONNULL_END
#import "ProductB.h"
@implementation ProductB
-(void)productMethod
{
}
@end
- SimpleFactory
#import <Foundation/Foundation.h>
@class ProductA,ProductB;
NS_ASSUME_NONNULL_BEGIN
@interface SimpleFactory : NSObject
+(id)createProduct:(NSString *)productName;
@end
NS_ASSUME_NONNULL_END
#import "SimpleFactory.h"
#import "ProductA.h"
#import "ProductB.h"
@implementation SimpleFactory
+(id)createProduct:(NSString *)productName
{
if ([productName isEqualToString:NSStringFromClass([ProductA class])]) {
return [[ProductA alloc] init];
} else if ([productName isEqualToString:NSStringFromClass([ProductB class])]) {
return [[ProductB alloc] init];
} else {
return nil;
}
}
@end
- 使用
ProductA *a = [SimpleFactory createProduct:NSStringFromClass([ProductA class])];
[a productMethod];
ProductB *b = [SimpleFactory createProduct:NSStringFromClass([ProductB class])];
[b productMethod];