OC语言 单例模式

来源:互联网 发布:网络银行交易规模 编辑:程序博客网 时间:2024/06/10 20:48

单例模式



ViewController.m



//

//  ViewController.m

//  Tank-OC10-01

//

//  Created by ibokan on 15/12/22.

//  Copyright © 2015谭其伟. All rights reserved.

//


#import "ViewController.h"


#import "Student.h"

@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    

    /*

     设计模式(用来解决编程某些特定问题) ---单例模式

     

     

     单例模式

     什么时候使用单例模式?

     在一个工程中,一些类只需要一个实例变量,我们就可以将这些类设计成单例模式

     

     单例模式的作用?

     当一个'A'被设计成单例模式时,'A'构造出的实例对象之于其他类来yfjj为全局实例对象,即在每一个类中由A构造出的实例对象,都未相同的对象.

     

     单例模式的实现思路:一个类只能创建一个实例和一个获得该实例的方法.

     

     */

    

    

    Student *st1 = [Student shareInstance];     //为空

    Student *st2 = [[Student alloc]init];       //也为空

    

    //copy创建第三个对象,

    Student *st3 = [st2 copy];

    

    

    

    if (st1 == st2) {

        NSLog(@"st1 = st2");

    }

    else

    {

        NSLog(@"st1 != st2");

    }

    

    

    //判断st2是否与copy 出来的 st3.  为了防止coPy出新的st3,作了copyWithZone这个方法,从而使得即是copy出来也还是一样的值.

    

    if (st3 == st2) {

        NSLog(@"st3 = st2");

    }

    else

    {

        NSLog(@"st3 != st2");

    }

    

    

    

    

    

    

    

    

    

    

    

    

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end








Student.h  student类////  Student.h//  Tank-OC10-01////  Created by ibokan on 15/12/22.//  Copyright © 2015年 谭其伟. All rights reserved.//#import <Foundation/Foundation.h>@interface Student : NSObject//1.在要被设计成单例的类的.h文件中声明一个构造单例方法+(Student *)shareInstance;     //分享实例,,类方法@end



Student.m  student类


//

//  Student.m

//  Tank-OC10-01

//

//  Created by ibokan on 15/12/22.

//  Copyright © 2015谭其伟. All rights reserved.

//


#import "Student.h"


//声明一个静态实例对象st,只会在第一次执行

static Student *st = nil;



@implementation Student



//2.实现该方法

+(Student *)shareInstance

{

    if (st == nil) {  //保证第一次执行

        st = [[Student alloc]init];  //检查该变量是否为nil,如果是就创建一个新的实例赋给全局实例,最后返回全局实例.

    }

    return st;       //这一步确保st为第一次使用

}



//为了防止alloc new 创建新的实例变量

+(id)allocWithZone:(struct _NSZone *)zone

{

    /*

     关于 @synchronized(self)

     @synchronized的作用是创建一个互斥锁,保证此时没有其他线程对self对象进行修改

     这个是Objective-C的一个锁令牌,防止self对象在同一时间内被其他线程访问,起到线程保护作用,一般在公用变量的时候使用,例如单例模式或者操作类的static变量中使用.

     

     */

    

    

    

    @synchronized(self) {    

        if (st ==nil) {

            st = [superallocWithZone:zone];

        }


    }

    return st;

}



//为了防止copy产生出新的对象,需要实现NSCopying协议

-(id)copyWithZone:(NSZone *)zone

{

    return self;

}






@end






输出:2015-12-22 15:24:25.169 Tank-OC10-01[22293:210353] st1 = st22015-12-22 15:24:25.170 Tank-OC10-01[22293:210353] st3 = st2




0 0
原创粉丝点击