iOS设计模式解析(二)抽象工厂方法

  • 抽象工厂方法:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类
  • 与工厂方法区别
    •   抽象工厂通过对象组合创建抽象产品、工厂通过类集成创建抽象产品
    •   抽象工厂创建多系列产品、工厂创建一种产品(例如上篇都属于鞋)
    •       抽象工厂修改父类的接口才能支持新产品、工厂子类化并重写工厂方法创建新产品
  • 例如      :Button类有两个子类ButtonA、ButtonB,我们通过对Button提供一个抽象工厂方法来产生不同的button子类:  
  • 代码实现
     1 #import "button.h"
     2 #import "buttonA.h"
     3 #import "buttonB.h"
     4 @implementation button
     5 +(instancetype)initWithType:(ButtonType)type
     6 {
     7     switch (type) {
     8         case ButtonTypeA:
     9             return [[buttonA alloc]init];
    10             break;
    11         case ButtonTypeB:
    12             return [[buttonB alloc]init];
    13             break;
    14         default:
    15             break;
    16     }
    17 }
    18 
    19 -(NSString *)name{
    20     return nil;
    21 }
    22 @end
    button
    1 #import "buttonB.h"
    2 
    3 @implementation buttonB
    4 -(NSString *)name{
    5     return @"B";
    6 }
    7 @end
    buttonB
    1 #import "buttonA.h"
    2 
    3 @implementation buttonA
    4 -(NSString *)name{
    5     return @"A";
    6 }
    7 @end
    buttonA
     1 #import "ViewController.h"
     2 #import "button.h"
     3 #import "buttonA.h"
     4 #import "buttonB.h"
     5 @interface ViewController ()
     6 
     7 @end
     8 
     9 @implementation ViewController
    10 
    11 - (void)viewDidLoad {
    12     [super viewDidLoad];
    13 
    14     buttonA * buttonA = [button initWithType:ButtonTypeA];
    15     NSLog(@"%@",buttonA.name);
    16     
    17     buttonB * buttonB = [button initWithType:ButtonTypeB];
    18     NSLog(@"%@",buttonB.name);
    19     
    20           
    21     
    22 }
    23 
    24 - (void)didReceiveMemoryWarning {
    25     [super didReceiveMemoryWarning];
    26 }
    27 
    28 @end
    ViewController
  • 打印结果

    2016-05-09 16:16:43.062 Factory[2671:193558] A

    2016-05-09 16:16:43.063 Factory[2671:193558] B

  • 总结:其实工厂方法就是生产一种固定产品(比如鞋子,可以继续扩展成AD、PUMA等等)。而且抽象工厂就是生产不同类产品的全部产品(可以随便添加产品族,比如扩展一个衣服类等等)

     

posted @ 2016-05-09 16:26  conor  阅读(294)  评论(0编辑  收藏  举报