士兵突击,是用Objective-C语言实现的一个面向对象的案例。
一、原理分析士兵要射击,需要有枪。枪要开火,需要有弹夹。弹夹装子弹,需要判断子弹数量是否大于最大装弹量。
原则就是自己的事情自己做,判断装弹量是否大于0,并且小于最大装弹量,是弹夹的事儿。
判断弹夹里是否还有子弹,是枪在射击时的事儿,如果有子弹,则可以射击。
士兵射击,需要有把枪,士兵有了枪才能射击。
#import
/// 弹夹类
@interface DanJia : NSObject
{
///最大装弹数
int _maxCapacity;
///现有子弹数
int _bulletCount;
}
-
(void)setMaxCapacity:(int)maxCapacity;
-
(int)maxCapacity;
-
(void)setBulletCount:(int)bulletCount;
-
(int)bulletCount;
@end
#import “DanJia.h”
@implementation DanJia
-
(void)setMaxCapacity:(int)maxCapacity
{
_maxCapacity = maxCapacity;
} -
(int)maxCapacity
{
return _maxCapacity;
} -
(void)setBulletCount:(int)bulletCount
{
if(bulletCount>= 0 && bulletCount <= _maxCapacity)
{
_bulletCount = bulletCount;
}
else
{
_bulletCount = 10;
}
}
- (int)bulletCount
{
return _bulletCount;
}
@end
#import
#import “DanJia.h”
///枪类
@interface Gun : NSObject
{
NSString *_model;
int _sheCheng;
DanJia *_danJia;
//int _bulletCount;
}
-
(void)setModel:(NSString *)model;
-
(NSString *)model;
-
(void)setSheCheng:(int)sheCheng;
-
(int)sheCheng;
-
(void)setDanJia:(DanJia *)danJia;
-
(DanJia *)danJia;
//- (void)setBulletCount:(int)bulletCount;
//- (int)bulletCount;
- (void)shoot;
@end
#import “Gun.h”
@implementation Gun
-
(void)setModel:(NSString *)model
{
_model = model;
} -
(NSString *)model
{
return _model;
} -
(void)setSheCheng:(int)sheCheng
{
_sheCheng = sheCheng;
} -
(int)sheCheng
{
return _sheCheng;
} -
(void)setDanJia:(DanJia *)danJia
{
_danJia = danJia;
} -
(DanJia *)danJia
{
return _danJia;
}
//- (void)setBulletCount:(int)bulletCount
//{
// _bulletCount = bulletCount;
//}
//- (int)bulletCount
//{
// return _bulletCount;
//}
- (void)shoot
{
//1.先判断当前枪对象的弹夹中是否还有子弹
if([_danJia bulletCount] > 0)
{
NSLog(@“突突突…”);
//突突突完以后,弹夹里的子弹数量要减少1;
int count = [_danJia bulletCount];
[_danJia setBulletCount:–count];
NSLog(@“剩余子弹数量:%d”,count);
}
else
{
NSLog(@“子弹都没有,突突突毛线啊。。。”);
}
}
@end
#import
#import “Gun.h”
@interface Soldier : NSObject
{
NSString *_name;
NSString *_type;
Gun *_gun;
}
-
(void)setName:(NSString *)name;
-
(NSString *)name;
-
(void)setType:(NSString *)type;
-
(NSString *)type;
-
(void)setGun:(Gun *)gun;
-
(Gun *)gun;
-
(void)fire;
@end
#import “Soldier.h”
@implementation Soldier
-
(void)setName:(NSString *)name
{
_name = name;
} -
(NSString *)name
{
return _name;
} -
(void)setType:(NSString *)type
{
_type = type;
} -
(NSString *)type
{
return _type;
} -
(void)setGun:(Gun *)gun
{
_gun = gun;
} -
(Gun *)gun
{
return _gun;
} -
(void)fire
{
NSLog(@“预备,开火…”);
[_gun shoot];
}
@end
#import
#import “Soldier.h”
int main()
{
DanJia *dj = [DanJia new];
[dj setMaxCapacity:100];
[dj setBulletCount:50];
Gun *ak47 = [Gun new];
[ak47 setModel:@“Ak47”];
[ak47 setDanJia:dj];
//[ak47 setBulletCount:100];
Soldier *xsd = [Soldier new];
[xsd setName:@"许三多"];
[xsd setType:@"炮兵"];
[xsd setGun:ak47];
for(int i = 0 ; i < 100 ; i++)
[xsd fire];
return 0;
}
总结以上这7个文件,分别复制到相应的文件里,运行即可。



