Objective C 模板方法模式
来源:互联网 发布:mysql mac安装教程 编辑:程序博客网 时间:2024/06/09 16:13
模板方法模式,定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
下面和给大家展示一下类的结构图:
其实,结构很简单,只有两层关系,核心思想就是把公共方法向上提到父类中。代码实现起来也不复杂。下面还是老样子,向大家简单展示一下代码如何实现。
============================================
AbstractClass类接口
1
2
3
4
5
6
7
#import <Foundation/Foundation.h>
@interface
AbstractClass :
NSObject
-(
void
)PrimitiveOperation1;
-(
void
)PrimitiveOperation2;
-(
void
)TemplateMethod;
@end
AbstractClass类实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#import "AbstractClass.h"
@implementation
AbstractClass
-(
void
)PrimitiveOperation1{
return
;
}
-(
void
)PrimitiveOperation2{
return
;
}
-(
void
)TemplateMethod{
[
self
PrimitiveOperation1];
[
self
PrimitiveOperation2];
return
;
}
@end
ConcreteClassA类接口
1
2
3
4
#import "AbstractClass.h"
@interface
ConcreteClassA:AbstractClass
@end
ConcreteClassA类实现
1
2
3
4
5
6
7
8
9
10
#import "ConcreteClassA.h"
@implementation
ConcreteClassA
-(
void
)PrimitiveOperation1{
NSLog
(@
"具体类A方法1实现"
);
}
-(
void
)PrimitiveOperation2{
NSLog
(@
"具体类A方法2实现"
);
}
@end
ConcreteClassB类接口
1
2
3
4
#import "AbstractClass.h"
@interface
ConcreteClassB:AbstractClass
@end
ConcreteClassB类实现
1
2
3
4
5
6
7
8
9
10
#import "ConcreteClassB.h"
@implementation
ConcreteClassB
-(
void
)PrimitiveOperation1{
NSLog
(@
"具体类B方法1实现"
);
}
-(
void
)PrimitiveOperation2{
NSLog
(@
"具体类B方法2实现"
);
}
@end
Main方法调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#import <Foundation/Foundation.h>
#import "ConcreteClassA.h"
#import "ConcreteClassB.h"
int
main (
int
argc,
const
char
* argv[])
{
@autoreleasepool
{
AbstractClass *c = [[ConcreteClassA alloc]init];
[c TemplateMethod];
c = [[ConcreteClassB alloc]init];
[c TemplateMethod];
}
return
0;
}
代码展示完毕!其实,模板方法模式就是提供了一个很好的代码复用平台,当不变的和可变的行为在方法的子类实现中混合在一起的时候,不变的行为就会在子类中重复出现。我们通过模板方法模式把这些行为搬移到单一的地方,这样就帮助子类摆脱重复的不变行为的纠缠。
- Objective C--模板方法模式
- Objective C 模板方法模式
- Objective C--模板方法模式
- Objective C--工厂方法模式
- Objective C 工厂方法模式
- Objective C--工厂方法模式
- 在objective-c中实现模板方法模式(template method)
- 【C++】Chapter7:模板方法模式
- 设计模式_模板方法模式(C++)
- 从C++到objective-c----委托(模板方法)
- 从C++到objective-c----委托(模板方法)
- Objective-C 委托模式
- Objective C--观察者模式
- Objective C--外观模式
- Objective C--原型模式
- Objective C--访问者模式
- Objective C--命令模式
- Objective C--代理模式
- GDB 调试程序
- TCP/IP详解学习笔记(2)-数据链路层
- 程序员零起步(三)——求职面试
- main 带参数 简单说明
- Content Provider 基础
- Objective C 模板方法模式
- TCP/IP详解学习笔记(3)-IP协议,ARP协议,RARP协议
- MyEclipse优化
- 用c.vim插件打造C/C++集成编辑器
- JNI与JNA性能比较
- TCP/IP详解学习笔记(4)-ICMP协议,ping和Traceroute
- LINQ TO XML C#实例 类和XML文件互转换
- const指针的了解
- ADADMIN - Generate Applications Files 菜单项详解