工廠模式:工廠方法
- 定義一個用于創(chuàng)建對象的接口,讓子類決定實例化哪一個類。工廠方法使一個類的實例化延遲到其子類觉义。
工廠方法UML
demo實現(xiàn)
- ColorViewGenerator(抽象類)
#import <Foundation/Foundation.h>
#import "RedView.h"
#import "BlueView.h"
@interface ColorViewGenerator : NSObject
- (ColorView *)colorViewWithFrame:(CGRect)rect;
@end
#import "ColorViewGenerator.h"
@implementation ColorViewGenerator
- (ColorView *)colorViewWithFrame:(CGRect)rect
{
return [[ColorView alloc] initWithFrame:rect];
}
@end
- RedViewGenerator(類)
#import "ColorViewGenerator.h"
@interface RedViewGenerator : ColorViewGenerator
@end
#import "RedViewGenerator.h"
@implementation RedViewGenerator
- (ColorView *)colorViewWithFrame:(CGRect)rect
{
return [[RedView alloc] initWithFrame:rect];
}
@end
- BlueViewGenrator(product類)
#import "ColorViewGenerator.h"
@interface BlueViewGenrator : ColorViewGenerator
@end
#import "BlueViewGenrator.h"
@implementation BlueViewGenrator
- (ColorView *)colorViewWithFrame:(CGRect)rect
{
return [[BlueView alloc] initWithFrame:rect];
}
@end
- ColorView 類(product 類)
#import <UIKit/UIKit.h>
@interface ColorView : UIView
@end
#import "ColorView.h"
@implementation ColorView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor grayColor];
}
return self;
}
@end
- RedView 類(子類)
#import "ColorView.h"
@interface RedView : ColorView
@end
#import "RedView.h"
@implementation RedView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor redColor];
UIImage *backGroundImage = [UIImage imageNamed:@"2"];
UIImageView *backImageView = [[UIImageView alloc] initWithImage:backGroundImage];
[self addSubview: backImageView];
}
return self;
}
@end
- BlueView 子類
#import "ColorView.h"
@interface BlueView : ColorView
@end
#import "BlueView.h"
@implementation BlueView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor blueColor];
UIImage *backGroundImage = [UIImage imageNamed:@"3"];
UIImageView *backImageView = [[UIImageView alloc] initWithImage:backGroundImage];
[self addSubview: backImageView];
}
return self;
}
@end
- ViewController 類
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
#import "ViewController.h"
#import "BlueViewGenrator.h"
#import "RedViewGenerator.h"
#import "RedView.h"
#import "BlueView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
RedView *redview = (RedView *)[[RedViewGenerator alloc] colorViewWithFrame:self.view.bounds];
[self.view addSubview: redview];
BlueView *blueView = (BlueView *) [[BlueViewGenrator alloc] colorViewWithFrame:self.view.bounds];
[self.view addSubview: blueView];
}
@end