//main.m
//单例模式:
// 对象在任何时候,都只有一个,好处是在多个类之间共享数据
//设计要点:
// (1)保证唯一,程序在运行期间必须唯一
// (2)单例类,必须提供一个接入点
#import <Foundation/Foundation.h>
#import "Animal.h"
#import "Mammal.h"
#import "Dog.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Mammal *mammal = [Mammal new];
[mammal growUp];
Dog *dog = [Dog new];
[dog growUp];
}
return 0;
}
//Animal.h
#import <Foundation/Foundation.h>
@interface Animal : NSObject<NSCopying>
@property (nonatomic,copy)NSString *trait;
+(instancetype)shareInstance;
@end
//Animal.m
#import "Animal.h"
//定义一个全局变量
static Animal *instance = nil;
@implementation Animal
-(id)copyWithZone:(NSZone*)zone{
return self;
}
+(id)allocWithZone:(NSZone *)zone{
//线程保护
@synchronized(self){
if(instance==nil){
//调用父类的alloc
instance = [super allocWithZone:zone];
return instance;
}
}
return instance;
}
-(id)retain{
return self;
}
-(NSUInteger)retainCount{
return NSUIntegerMax;
}
-(oneway void)release{
}
-(id)autorelease{
return self;
}
////单例的接入点的方法
+(instancetype)shareInstance{
////目的:保证对象必须唯一
if(instance ==nil){
//创建一个对象
instance = [[Animal alloc]init];
}
return instance;
}
@end
Mammal.h
#import <Foundation/Foundation.h>
@interface Mammal : NSObject
-(void)growUp;
@end
//Mammal.m
#import "Mammal.h"
#import "Animal.h"
@implementation Mammal
-(void)growUp{
Animal *animal = [Animal shareInstance];
animal.trait = @"我小时候是吃奶长大的";
}
@end
//Dog.h
#import <Foundation/Foundation.h>
@interface Dog : NSObject
-(void)growUp;
@end
//Dog.m
#import "Dog.h"
#import "Animal.h"
@implementation Dog
-(void)growUp{
// Animal *animal = [Animal shareInstance];
// 改进的单例模式
Animal *animal = [[Animal alloc]init];
NSLog(@"%@",animal.trait);
}
@end
//如有错误,敬请指正。
//既然来过,留下脚印在走吧。{:3_53:} |
|