ios设计模式4-桥接模式

来源:互联网 发布:淘宝客推广流程 编辑:程序博客网 时间:2024/05/21 08:37

ios设计模式4-桥接模式

  在现实生活中,我们总是遇到根据事物的不同特性进行分类的情况,为了使得能够事物类型能够轻松按照多个特点进行变化又不增加复杂度,桥接模式应运而生。今天举个学校学生选课的例子,,,最近选课很麻烦啊,大四了选修不够分还得选课,但是学校久久不开放教务系统让我们选,,,好了,入正题,举例我们是要选数学课,数学分为高数和数学分析,我们有计算机系,有数学系的同学要选课,那么怎么表示他们之间的关系呢,根据设计模式的基本原则中的依赖倒转原则,我们是抽象编程,所以先来个抽象类math:
#import "Math.h"@implementation Math-(void)select{    }@end


里面只有一个方法,由于oc没有表示抽象类的办法,所以留个空函数,然后是高数,和数学分析了,他们都继承自math:

#import "AdvanceMath.h"@implementation AdvanceMath-(void)select{    NSLog(@"选择了高等数学");}@end


#import "MathAnalysis.h"@implementation MathAnalysis-(void)select{    NSLog(@"选了数学分析");}@end
然后是合成聚合原则,我们建一个系departments类,里面使用math对象:
代码如下:
#import "Departments.h"@implementation Departments-(void)select{    }-(void)setCourse:(Math*)math{    self->mathcourse = math;}@end
系又分为计算机系,数学系:
#import "Computer.h"@implementation Computer-(void)select{    NSLog(@"coumputer department select");    [mathcourse select];}@end

////  Mathematics.m//  ios设计模式4桥接模式//#import "Mathematics.h"@implementation Mathematics-(void)select{    NSLog(@"mathematics select");    [mathcourse select];    }@end
departments就是课程和院系的桥梁了,符合迪米特原则,这就是桥接模式的美妙,要是要增加院系,或者其他数学类的类,只要继承math,或者departments就可以了,符合开放闭合原则,只增加,避免了修改。
好了,主函数测试:
#import <Foundation/Foundation.h>#import "Departments.h"#import "Computer.h"#import "MathAnalysis.h"#import "AdvanceMath.h"#import "Mathematics.h"int main(int argc, const char * argv[]) {    @autoreleasepool {        // insert code here...    //    NSLog(@"Hello, World!");        Departments * department = nil;        department = [[Computer alloc]init];        [department setCourse:[[AdvanceMath alloc]init]];
        [department select];        department = [[Mathematics alloc]init];        [department setCourse:[[MathAnalysis alloc]init]];        [department select];            }    return 0;}

首先是计算机系选课,选了高数,然后是数学系的选课,选了数学分析,结果如下:
2015-12-28 00:18:18.136 ios设计模式4桥接模式[789:18392] Hello, World!2015-12-28 00:18:18.137 ios设计模式4桥接模式[789:18392] coumputer department select2015-12-28 00:18:18.138 ios设计模式4桥接模式[789:18392] 选择了高等数学2015-12-28 00:18:18.138 ios设计模式4桥接模式[789:18392] mathematics select2015-12-28 00:18:18.138 ios设计模式4桥接模式[789:18392] 选了数学分析Program ended with exit code: 0

总结

桥接模式从效果上来说解除了不同分类之间的耦合性,使其可以独立变化,体现设计模式的精髓啊!




0 0
原创粉丝点击