今天整理电脑打开一次自我Objective-C当编写一个实践设计模式委托一个小程序,在po快来分享。也复习一下OC中的托付。

Objective-C中的托付设计模式是和协议分不开的。

协议呢。就是使用了这个协议后就要依照这个协议来办事,协议要求实现的方法就一定要实现。

(在Objective-C2.0中能够在协议里选择是否必须实现某种方法,用keyword@optional和@required)

托付的话,顾名思义就是自己处理不了的事情。托付他人依照协议里写好的条款来办理这件事。

详细实现的步骤能够依照以下这样:

1.拟定一份协议,协议里包含了想要实现的事情(即方法)。

2.托付人类中设置一个遵守该协议的托付变量。

3.被托付人类中实现协议要求的方法。

4.把托付人中的托付变量设置成被托付人。

5.当事情发生时。用托付变量调用被托付人中的协议方法。

以下讲讲我写的这个例程。牛仔与姑娘。

故事背景是,在联邦政府还没有进入的荒野西部。一个善良漂亮的姑娘Lucy和父亲相依为命,过着艰苦可是还算幸福的生活。一天,一群土匪强盗的到来带走了Lucy的父亲。Lucy伤心至极。便托付好心的牛仔John Marston去挽救他的父亲。并将这群恶棍绳之以法。正义驱使John接下了这个活,并终于挽救了Lucy的父亲,并惩治了坏蛋。

好了,首先我们得先创建一份协议Wanted。包括两个方法。saveHerDad和killTheBadGuy。代码例如以下:

#import <Foundation/Foundation.h>

@protocol Wanted <NSObject>
@required -(int)saveHerDad;
-(void)killTheBadGuy; @end

接着。创建姑娘Girl类,在当中设置一个遵守Wanted协议的托付变量。使用helpHelp方法来触发事件。我用了定时器来模拟整个事件的发生,接口例如以下:

#import <Foundation/Foundation.h>
#import "Wanted.h"
@interface Girl : NSObject
{
}
@property(nonatomic,copy) NSString *name;
@property(nonatomic,assign) id <Wanted> delegate; -(id)initWithName:(NSString*)name WithDelegate:(id<Wanted>) delegate;
-(void)helpHelp; @end

实现例如以下:

#import "Girl.h"
#import "Cowboy.h" @interface Girl () -(void)seesTheCowboy:(NSTimer *)timer; @end @implementation Girl -(id)initWithName:(NSString*)name WithDelegate:(id<Wanted>) delegate{
self = [super init];
if (self) {
self.name = name;
self.delegate = delegate;
}
return self;
} -(void)helpHelp{
NSLog(@"%@:My name is %@,my dad was taken by the bad guys,can you save him,please?",self.name,self.name);
NSLog(@"%@:OK,young lady,wait for the good news!",self.delegate);
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(seesTheCowboy:) userInfo:@"My dad" repeats:YES];
} -(void)seesTheCowboy:(NSTimer *)timer{
if ([self.delegate respondsToSelector:@selector(saveHerDad)]) {
int i = [self.delegate saveHerDad];
if (i==0) {
NSLog(@"%@:My heart is so broken,I cant live without him,you must save him please,woo woo.",self.name);
printf("\n");
}else{
NSLog(@"%@:Thank you so much,marry me~",self.name);
[timer invalidate];
}
}
} @end

然后,创建牛仔Cowboy类,用他来实现协议Wanted中的方法,因为不想让外部调用协议中的方法。所以我们将协议中的方法设置为私有方法。接口例如以下:

#import <Foundation/Foundation.h>

@interface Cowboy : NSObject

@property (nonatomic,copy) NSString *name;

@end

实现例如以下:

#import "Cowboy.h"

@implementation Cowboy
static int result;
-(int)saveHerDad{
printf("\n");
result = [self killTheBadGuy];
if (result == 0) {
NSLog(@"%@:There are too many of'em,I'll take all of my men and kill them all!!!Wait for the good news!",self.name);
result++;
return 0;
}else{
NSLog(@"%@ and his crew:I killed all the bad guys,and here is your father.",self.name);
return 1;
}
} -(int)killTheBadGuy{
return result;
}
-(NSString *)description {
NSString *name = self.name;
return name;
}
@end

好了,接下来我们就開始等着事件发生了,我设置了定时器,两秒触发一次,当result值为0的时候,营救并不成功。我们的牛仔铩羽而归;当result值为1时,营救任务成功,挽救了Lucy的父亲。

主函数登场:

#import <Foundation/Foundation.h>
#import "Girl.h"
#import "Cowboy.h"
int main(int argc, const char * argv[])
{ @autoreleasepool {
Cowboy *cowboy = [[Cowboy alloc] init]; //创建Cowboy实例
cowboy.name = @"John Marston";
Girl *girl = [[Girl alloc] initWithName:@"Lucy" WithDelegate:cowboy]; //初始化girl,将cowboy作为托付人
[girl helpHelp]; //触发时间 NSDate *date = [NSDate date];
//设置定时器。程序共执行6秒
[[NSRunLoop currentRunLoop] runUntilDate:[date dateByAddingTimeInterval:6]];
}
return 0;
}

一切都准备就绪。如今让我们的牛仔拿起枪,行动起来吧。

编译成功!输出结果例如以下:

2014-07-16 17:27:10.973 Girl&Cowboy[4055:303] Lucy:My name is Lucy,my dad was taken by the bad guys,can you save him,please?

2014-07-16 17:27:11.012 Girl&Cowboy[4055:303] John Marston:OK,young lady,wait for the good news!

2014-07-16 17:27:13.014 Girl&Cowboy[4055:303] John Marston:There are too many of'em,I'll take all of my men and kill them all!!!Wait for the good news!

2014-07-16 17:27:13.015 Girl&Cowboy[4055:303] Lucy:My heart is so broken,I cant live without him,you must save him please,woo woo.

2014-07-16 17:27:15.014 Girl&Cowboy[4055:303] John Marston and his crew:I killed all the bad guys,and here is your father.

2014-07-16 17:27:15.015 Girl&Cowboy[4055:303] Lucy:Thank you so much,marry me~

Program ended with exit code: 0

我们的英雄把姑娘的父亲救出来了而且杀死了坏人。

这个样例非常easy,实际应用中会比这个复杂得多,可是希望通过我这个样例能让不了解的同学对托付设计模式有个初步的认识吧~

版权声明:本文博主原创文章,博客,未经同意不得转载。

[演示示例程序]Objective-C受委托的设计模式(牛仔女孩)的更多相关文章

  1. nginx subrequest演示示例程序

    只有简单subrequest应用演示示例. nginx.conf文件: #user nobody; worker_processes 1; #error_log logs/error.log; #er ...

  2. 通过Jexus 部署 dotnetcore版本MusicStore 示例程序

    ASPNET Music Store application 是一个展示最新的.NET 平台(包括.NET Core/Mono等)上使用MVC 和Entity Framework的示例程序,本文将展示 ...

  3. osg 示例程序解析之osgdelaunay

    osg 示例程序解析之osgdelaunay 转自:http://lzchenheng.blog.163.com/blog/static/838335362010821103038928/ 本示例程序 ...

  4. OSG中的示例程序简介

    OSG中的示例程序简介 转自:http://www.cnblogs.com/indif/archive/2011/05/13/2045136.html 1.example_osganimate一)演示 ...

  5. LTE Module User Documentation(翻译15)——示例程序、参考场景以及故障检测和调试技巧

    LTE用户文档 (如有不当的地方,欢迎指正!)     21 Examples Programs(示例程序)   路径 src/lte/examples/ 包含一些示例仿真程序,这些例子表明如何仿真不 ...

  6. OSG中的示例程序简介(转)

    OSG中的示例程序简介 1.example_osganimate一)演示了路径动画的使用 (AnimationPath.AnimationPathCallback),路径动画回调可以作用在Camera ...

  7. java 添加一个线程、创建响应的用户界面 。 演示示例代码

    javajava 添加一个线程.创建响应的用户界面 . 演示示例代码 来自thinking in java 4 21章  部分的代码  夹21.2.11 thinking in java 4免费下载: ...

  8. VS2012下基于Glut 矩阵变换示例程序2:

    在VS2012下基于Glut 矩阵变换示例程序:中我们在绘制甜圈或者圆柱时使用矩阵对相应的坐标进行变换后自己绘制甜圈或者圆柱.我们也可以使用glLoadMatrixf.glLoadMatrixd载入变 ...

  9. 部署Bookinfo示例程序详细过程和步骤(基于Kubernetes集群+Istio v1.0)

    部署Bookinfo示例程序详细过程和步骤(基于Kubernetes集群+Istio v1.0) 部署Bookinfo示例程序   在下载的Istio安装包的samples目录中包含了示例应用程序. ...

随机推荐

  1. [Angular] AuthService and AngularFire integration

    Config AngularFire, we need database and auth module from firebase. import {NgModule} from '@angular ...

  2. (转)利用openfiler实现iSCSI

    转自:http://czmmiao.iteye.com/blog/1735417 openfiler openfiler是一个基于浏览器的网络存储管理工具.来自于Linux系统.openfiler在一 ...

  3. hdu 3605 Escape 二分图的多重匹配(匈牙利算法)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3605 Escape Time Limit: 4000/2000 MS (Java/Others)    ...

  4. [Preact] Integrate react-router with Preact

    React-router is the community favourite routing solution - it can handle all of your complex routing ...

  5. [慕课笔记]mongodb入门篇

    一:对mongodb有一个系统的完备的了解,只有概念清楚了,才能更好的使用 二:学会mongodb数据库的搭建 首先:了解如何部署数据库的服务 搭建简单的单机服务到搭建具有冗余容错功能的复制集再到搭建 ...

  6. C++开发人脸性别识别教程(10)——加入图片的人脸检測程序

    现在我们的MFC框架已经初具规模,能够读取并显示目录下的图片.在这篇博文中我们将向当中加入人脸检測的程序. 一.人脸检測算法 这里我们使用OpenCv封装的Adaboost方法来进行人脸检測,參见:C ...

  7. 【24.67%】【codeforces 551C】 GukiZ hates Boxes

    time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...

  8. 【35.43%】【hdu 4347】The Closest M Points

    Time Limit: 16000/8000 MS (Java/Others)    Memory Limit: 98304/98304 K (Java/Others) Total Submissio ...

  9. Android改变图片颜色的自定义控件

    效果如下: 理解:Xfermode的16总模式如图 第一步: package com.rong.activity; import com.rong.test.R; import android.con ...

  10. php实现 句子逆序(需求才是最好的老师)

    php实现 句子逆序(需求才是最好的老师) 一.总结 一句话总结:需求才是最好的老师. 1.str_split()和explode()的区别? explode — 使用一个字符串分割另一个字符串 3 ...