@fiy-fish
2015-07-18T21:44:12.000000Z
字数 2230
阅读 1254
Objective-c
// main.m
// day07-04-单例
//
// Created by Aaron on 15/7/9.
// Copyright (c) 2015年 Aaron. All rights reserved.
//
#import <Foundation/Foundation.h>
//单例
//设计模式
//一个类只会产生一个实例,而且不释放
//这个实例叫做单例对象
//这个类叫做单例类
//单例的应用场景
//废纸篓
//网页计数器
//单例的作用: 共享数据,用作管理
#import "TaskManager.h"
#import "TaskOne.h"
#import "TaskTwo.h"
void test()
{
TaskManager *manager = [TaskManager defaultManager];
NSLog(@"%p",manager);
//day07-04-单例[2128:174387] 0x10030fea0
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
TaskManager *manager = [TaskManager defaultManager];
NSLog(@"%p",manager);
//day07-04-单例[2128:174387] 0x10030fea0
TaskOne *one = [[TaskOne alloc] init];
[one TaskRun];
TaskTwo *two = [[TaskTwo alloc] init];
[two TaskRun];
TaskTwo *two1 = [[TaskTwo alloc] init];
[two1 TaskRun];
//manager = nil;
[manager zhuxiao];
NSLog(@"%@",manager.taskArray);
//test();
}
return 0;
}
#import "Task.h"
@interface TaskOne : Task
@end
#import "TaskOne.h"
@implementation TaskOne
-(instancetype)init
{
if(self = [super init])
{
self.name = @"taskOne";
}
return self;
}
@end
#import "Task.h"
@interface TaskTwo : Task
//-(void)TaskRun;
@end
#import "TaskTwo.h"
#import "TaskManager.h"
@implementation TaskTwo
-(instancetype)init
{
if(self = [super init])
{
self.name = @"taskTwo";
}
return self;
}
-(void)TaskRun
{
TaskManager *manager = [TaskManager defaultManager];
NSLog(@"TaskTwo.h %p",manager);
//NSLog(@"%ld",manager.number);
}
@end
#import <Foundation/Foundation.h>
#import "Task.h"
@interface TaskManager : NSObject
@property (nonatomic,assign) NSInteger number;
@property (nonatomic,retain) NSMutableArray *taskArray;
//单例方法通常以default 或者share 开头
//单例类需要用单例方法来创建对象
+(instancetype)defaultManager;
-(void)addTask:(Task *)task;
-(void)zhuXiao;
@end
#import "TaskManager.h"
@implementation TaskManager
static TaskManager *manager = nil;
+(instancetype)defaultManager
{
// static TaskManager *manager = nil;
//加锁
@synchronized(self)
{
if(!manager)
{
manager = [[self alloc] init];
}
}
return manager;
}
-(void)zhuXiao
{
manager = nil;
}
-(void)addTask:(Task *)task
{
if(!_taskArray)
{
_taskArray = [NSMutableArray array];
}
[_taskArray addObject:task];
}
@end
#import <Foundation/Foundation.h>
@interface Task : NSObject
@property (nonatomic,copy) NSString *name;
-(void)TaskRun;
@end
#import "Task.h"
#import "TaskManager.h"
@implementation Task
-(void)TaskRun
{
TaskManager *manager = [TaskManager defaultManager];
NSLog(@"TaskOne.h %p",manager);
manager.number = 1000;
[manager addTask:self];
}
@end