简单工厂模式

2019-10-08  本文已影响0人  CaptainRoy
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@protocol Product <NSObject>

-(void)productMethod;

@end

NS_ASSUME_NONNULL_END
#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
#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
#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];
上一篇下一篇

猜你喜欢

热点阅读