- 工厂方法:定义创建对象的借口,让子类决定实例化哪一个类。工厂方法是一个类的实例化延迟到了子类
- 例如 :Shoes厂有两个子类(Newbalance、Nike)构建类图如下:
- 代码实现:
#import "shoes.h" @implementation shoes -(instancetype)initWithFrame:(CGRect)frame{
if (self == [super initWithFrame:frame]) {
//牌子
_band = @"Shoes";
}
return self;
} @endShoes
#import "NewBlance.h" @implementation NewBlance
-(instancetype)initWithFrame:(CGRect)frame{
if (self == [super initWithFrame:frame]) {
self.band = @"NewBlance";
}
return self;
} @endNewBlance
#import "Nike.h" @implementation Nike
-(instancetype)initWithFrame:(CGRect)frame{
if (self == [super initWithFrame:frame]) {
self.band = @"Nike";
}
return self;
} @endNike
#import "ViewController.h"
#import "NewBlance.h"
#import "Nike.h"
@interface ViewController () @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; NewBlance * shoeNB = [[NewBlance alloc]initWithFrame:CGRectZero];
NSLog(@"%@",shoeNB.band); Nike * shoeNike = [[Nike alloc]initWithFrame:CGRectZero];
NSLog(@"%@",shoeNike.band);
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
} @endViewController
- 打印结果:
2016-05-09 15:49:45.109 Factory[2416:181448] NewBlance
2016-05-09 15:49:45.110 Factory[2416:181448] Nike