#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];
网友评论