• 工厂方法:定义创建对象的借口,让子类决定实例化哪一个类。工厂方法是一个类的实例化延迟到了子类
  • 例如      :Shoes厂有两个子类(Newbalance、Nike)构建类图如下:  

  iOS设计模式解析(一)工厂方法-LMLPHP

  • 代码实现:

     #import "shoes.h"
    
     @implementation shoes
    
     -(instancetype)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
    //牌子
    _band = @"Shoes";
    }
    return self;
    } @end

    Shoes

     #import "NewBlance.h"
    
     @implementation NewBlance
    -(instancetype)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
    self.band = @"NewBlance";
    }
    return self;
    } @end

    NewBlance

     #import "Nike.h"
    
     @implementation Nike
    -(instancetype)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
    self.band = @"Nike";
    }
    return self;
    } @end

    Nike

     #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];
    } @end

    ViewController

  • 打印结果:

    2016-05-09 15:49:45.109 Factory[2416:181448] NewBlance

    2016-05-09 15:49:45.110 Factory[2416:181448] Nike

05-08 08:01