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

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

  

  • 代码实现
     1 #import "shoes.h"
     2 
     3 @implementation shoes
     4 
     5 -(instancetype)initWithFrame:(CGRect)frame{
     6     if (self == [super initWithFrame:frame]) {
     7         //牌子
     8         _band = @"Shoes";
     9     }
    10     return self;
    11 }
    12 
    13 @end
    Shoes
     1 #import "NewBlance.h"
     2 
     3 @implementation NewBlance
     4 -(instancetype)initWithFrame:(CGRect)frame{
     5     if (self == [super initWithFrame:frame]) {
     6         self.band = @"NewBlance";
     7     }
     8     return self;
     9 }
    10 
    11 @end
    NewBlance
     1 #import "Nike.h"
     2 
     3 @implementation Nike
     4 -(instancetype)initWithFrame:(CGRect)frame{
     5     if (self == [super initWithFrame:frame]) {
     6         self.band = @"Nike";
     7     }
     8     return self;
     9 }
    10 
    11 @end
    Nike
     1 #import "ViewController.h"
     2 #import "NewBlance.h"
     3 #import "Nike.h"
     4 @interface ViewController ()
     5 
     6 @end
     7 
     8 @implementation ViewController
     9 
    10 - (void)viewDidLoad {
    11     [super viewDidLoad];
    12     
    13     NewBlance * shoeNB   = [[NewBlance alloc]initWithFrame:CGRectZero];
    14     NSLog(@"%@",shoeNB.band);
    15 
    16     Nike      * shoeNike = [[Nike alloc]initWithFrame:CGRectZero];
    17     NSLog(@"%@",shoeNike.band);
    18 }
    19 
    20 - (void)didReceiveMemoryWarning {
    21     [super didReceiveMemoryWarning];
    22 }
    23 
    24 @end
    ViewController

     

  • 打印结果

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

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

posted @ 2016-05-09 15:52  conor  阅读(183)  评论(0编辑  收藏  举报