工廠模式-簡單工廠模式---簡介:? 工廠模式是創(chuàng)建類型的模式,為什么使用工廠模式?
原因:解除耦合
#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];
//也可以創(chuàng)建不同的類? 比如UIImageView? UITextField 等等
obj = [UIButton buttonWithType:UIButtonTypeContactAdd];
obj = [[UIButton alloc] init];
![IMAGE002](image/825CB5B5-01F5-4555-900A-7FF4AD8D878F.PNG)
相對應(yīng)于[**示例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];? ?
#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**也是用工廠模式寫的
上訴,說的不對的,請老鐵們斧正