工厂模式-简单工厂模式---简介: 工厂模式是创建类型的模式,为什么使用工厂模式?
原因:解除耦合
#import <Foundtion/Foundation.h>
#import <UIKIT/UIKit.h>
@interface ViewFactory : NSObject+ (NSObject *)creatView;
{return [[UIButton alloc] init];}
![IMAGE001](image/9F203959-9442-4094-B198-A655BC3E97E5.png)
由于[**示例1**](#markdown-pane)并不完善,相对来说 一个类只能生成一个对象,会造成大量不变,可以查看[**示例2**](#示例2)
@interface ViewFactory1 : NSObject
+ (NSObject *)creatView:(NSIntger):chose;
+ (NSObject *)creatView:(NSIntger):chose
{case 1:obj = [[UIButton alloc] init];
//也可以创建不同的类 比如UIImageView UITextField 等等
obj = [UIButton buttonWithType:UIButtonTypeContactAdd];
obj = [[UIButton alloc] init];
![IMAGE002](image/825CB5B5-01F5-4555-900A-7FF4AD8D878F.PNG)
相对应于[**示例2**](#示例2), 如果添加新的类,就需要不停的更改ViewFactory类文件,这是我们不想看到的,频繁的更改中间文件,所以我们拓展了[**示例3**](#示例3)
[ViewFactoryConfing](image/ViewFactoryConfing.xml)
{ kCreatedControlTypeButton = 1,
kCreatedControlTypeImageView = 2
@interface ViewFactory : NSObject
+ (id)getInstance:(NSInteger)chosse;
+ (id)getInstance:(NSInteger)chosse {
ViewXmlParser *parser = [[ViewXmlParser alloc] init];
NSMutableDictionary *dict = [parser parser];
NSString *className = [NSString stringWithFormat:@"%ld",(long)chosse];
return [[[NSClassFromString([dict objectForKey:className]) class] alloc] init];}
@interface ViewXmlParser : NSObject
- (NSMutableDictionary *)parser;
@property (nonatomic, strong) NSMutableDictionary *dict;
@property (nonatomic, strong) NSString *currentElementName;
_dict = [NSMutableDictionary dictionary];
- (NSMutableDictionary *)parser {
NSString *path = [[NSBundle mainBundle] pathForResource:@"ViewFactoryConfing" ofType:@"xml"];
NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url]; parser.delegate = self;
#pragma mark - NSXMLParserDelegate
_currentElementName = elementName;
if ([elementName isEqualToString:@"view"]) {
NSString *key = [attributeDict objectForKey:@"key"];
NSString *className = [attributeDict objectForKey:@"className"];
[_dict setObject:className forKey:key];
}
}
```
相对来说[示例3](#示例3)只需要**ViewFacyoryConfing.xml**这个配置文件, 其实苹果的**故事版**和**XIB**也是用工厂模式写的
上诉,说的不对的,请老铁们斧正
网友评论