設計模式-(2)工廠方法
阿新 • • 發佈:2018-12-30
一,工廠方法模式
工廠方法模式:定義建立物件的介面,讓子類決定例項化那一個類。工廠方法使得類的例項化延遲到其子類。
靜態類結構圖:
Product:產品抽象類,定義產品物件的建立介面。
ConcreteProduct:實現Product介面的具體產品類。
Creator:定義返回Product物件的工廠方法,也可以提供工廠方法的預設實現。
ConcreteCreator:Creator子類,過載了工廠方法。返回ConcreteProduct物件。
二,工廠方法的使用場景
1,編譯時無法準確預期要建立的物件的類;
2,類想讓子類決定執行時建立什麼物件;
3,類有若干個輔助子類,開發者希望將返回哪個子類這個資訊區域性化;
使用工廠方法模式最低限度時,工廠方法能夠給予類在變更返回哪一種物件這個問題上更多的靈活性。適用情況:“一個類無法預期需要生成哪個類的物件,想讓其子類來指定所生成的物件。”
三,工廠方法建立物件更加安全
和直接建立新物件相比,工廠方法模式讓客戶程式可以要求由工程方法建立的物件有一組共同的行為。這樣往類層次結構中引入新的具體產品並不需修改客戶端程式碼,因為返回任何具體物件的介面根客戶端一直使用的介面相同。
四,程式碼
接下來我們用程式碼演示一下:
@interface ZGYShape : NSObject
- (void)draw;
@end
@implementation ZGYShape - (void)draw{ if ([self isKindOfClass:[ZGYShape class]]) { NSLog(@"ZGYShape類的draw方法"); }else{ [NSException raise:NSInternalInconsistencyException format:[NSString stringWithUTF8String:object_getClassName(self)],NSStringFromSelector(_cmd)]; NSLog(@"ZGYShape子類呼叫了draw方法,子類沒有重寫draw方法,屬於異常!"); } } @end
@interface ZGYCircleShape : ZGYShape
@end
@implementation ZGYCircleShape
- (void)draw{
NSLog(@"繪製一個圓形");
}
@end
@interface ZGYSquareShape : ZGYShape
@end
@implementation ZGYSquareShape
- (void)draw{
NSLog(@"繪製一個方形");
}
@end
#import "ZGYShape.h" @interface ZGYShapeFactory : NSObject - (ZGYShape *)factoryMethod; @end
@implementation ZGYShapeFactory
- (ZGYShape *)factoryMethod{
[NSException raise:NSInternalInconsistencyException
format:[NSString stringWithUTF8String:object_getClassName(self)],NSStringFromSelector(_cmd)];
return nil;
}
@end
@interface ZGYCircleShapeFactory : ZGYShapeFactory
@end
#import "ZGYCircleShape.h"
@implementation ZGYCircleShapeFactory
- (ZGYShape *)factoryMethod{
return [[ZGYCircleShape alloc]init];
}
@end
@interface ZGYSquareShapeFactory : ZGYShapeFactory
@end
#import "ZGYSquareShape.h"
@implementation ZGYSquareShapeFactory
- (ZGYShape *)factoryMethod{
return [[ZGYSquareShape alloc]init];
}
@end
#import "ZGYShape.h"
#import "ZGYCircleShapeFactory.h"
#import "ZGYSquareShapeFactory.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//工廠物件
ZGYCircleShapeFactory * circleShapeFactory = [[ZGYCircleShapeFactory alloc]init];
ZGYSquareShapeFactory * squareShapeFactory = [[ZGYSquareShapeFactory alloc]init];
//產品物件
ZGYShape * circleShape = [circleShapeFactory factoryMethod];
ZGYShape * squareShape = [squareShapeFactory factoryMethod];
//檢視物件
[circleShape draw];
[squareShape draw];
}
@end
最終的列印輸出
2017-09-30 22:57:14.399386+0800 設計模式(工廠方法模式)[63815:21286029] 繪製一個圓形
2017-09-30 22:57:14.399486+0800 設計模式(工廠方法模式)[63815:21286029] 繪製一個方形