首页 > 代码库 > 面向对象程序设计
面向对象程序设计
问题:把大象放入冰箱
一、面向过程
注重业务功能
1、打开冰箱的门
2、把大象放入冰箱
3、关闭冰箱的门
二、面向对象
注重功能的封装和层次
1、对象1:冰箱
功能:打开冰箱门、放入东西、关闭冰箱门
2、对象2:大象
代码演示:
1 // 2 // Fridge.m 3 // 面向对象 4 // 5 // Created by macos on 14-8-10. 6 // Copyright (c) 2014年 macos. All rights reserved. 7 // 8 9 #import "Fridge.h"10 11 @implementation Fridge12 @synthesize name,opend,array;13 -(id) initWidthName:(NSString *)iname14 {15 if (self = [super init]) {16 self.name = iname;17 opend = false;18 self.array = [[NSMutableArray alloc] init];19 NSLog(@"初始化一台:%@电冰箱",self.name);20 }21 return self;22 }23 24 -(BOOL) openDoor25 {26 if (opend) {27 NSLog(@"门已经打开,关闭后才能打开");28 }29 else30 {31 opend = true;32 NSLog(@"成功打开冰箱的门");33 }34 return opend;35 }36 37 -(BOOL) putIn:(id)something38 {39 if (opend) {40 [array addObject:something];41 NSLog(@"%@成功放入冰箱中,物品数量%lu",something,[array count]);42 }43 else44 {45 NSLog(@"%@不能放入冰箱中,物品数量%lu:冰箱门未打开",something,[array count]);46 }47 return opend;48 }49 50 -(BOOL) closeDoor51 {52 if (opend) {53 opend = false;54 NSLog(@"成功关闭冰箱的门");55 }56 else57 {58 NSLog(@"无法关闭冰箱的门:门已经关闭");59 }60 return opend;61 }62 @end
1 // 2 // Elephant.m 3 // 面向对象 4 // 5 // Created by macos on 14-8-10. 6 // Copyright (c) 2014年 macos. All rights reserved. 7 // 8 9 #import "Elephant.h"10 11 @implementation Elephant12 @synthesize name;13 14 -(id) initWidthName:(NSString *) iname15 {16 NSLog(@"初始化一头:%@象",iname);17 if (self = [super init]) {18 self.name=iname;19 }20 return self;21 }22 23 -(NSString *) description24 {25 return [[NSString alloc] initWithFormat:@"[%@象]",self.name];26 }27 @end
1 // 2 // main.m 3 // OOPDemo 4 // 5 // Created by macos on 14-8-10. 6 // Copyright (c) 2014年 macos. All rights reserved. 7 // 面向对象设计模式 8 9 #import <Foundation/Foundation.h>10 #import "Fridge.h"11 #import "Elephant.h"12 13 int main(int argc, const char * argv[])14 {15 16 @autoreleasepool {17 Fridge *fridge = [[Fridge alloc] initWidthName:@"海尔"];18 Elephant *elephant = [[Elephant alloc] initWidthName:@"南美洲"];19 [fridge openDoor] &&20 fridge.opend &&21 [fridge putIn:elephant] &&22 [fridge closeDoor];23 }24 return 0;25 }
1 2014-08-10 04:55:47.890 OOPDemo[2625:303] 初始化一台:海尔电冰箱2 2014-08-10 04:55:48.029 OOPDemo[2625:303] 初始化一头:南美洲象3 2014-08-10 04:55:48.036 OOPDemo[2625:303] 成功打开冰箱的门4 2014-08-10 04:55:48.047 OOPDemo[2625:303] [南美洲象]成功放入冰箱中,物品数量15 2014-08-10 04:55:48.053 OOPDemo[2625:303] 成功关闭冰箱的门6 Program ended with exit code: 0
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。