Objective-c语言_单例模式

单例模式这么理解呢

如学生类创建的学生都是同一个人,这是:单例模式


ViewController.m

#import "ViewController.h"

#import "Student.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    /*

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

     

     单例模式

     什么时候使用单例模式?

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

     

     单例模式的作用?

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

     

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

     

     */

    

    Student *st1 = [Student shareInstance];

    Student *st2 = [[Student alloc]init];

    

    Student *st3 = [st2 copy];

    

    if (st2 == st3)

    {

        NSLog(@"st2 = st3");

    }

    else

        

    {

        NSLog(@"st2 != st3");

    }

    

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end

==========================================================================

Student.h

#import <Foundation/Foundation.h>


@interface Student : NSObject


//1.在要被设计成单例的类的.h文件中声明一个构造单例方法

+(Student *)shareInstance ;


@end

==========================================================================

Student.m

#import "Student.h"


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

static Student *st = nil;


@implementation Student


//2.实现该方法

+(Student *)shareInstance

{

    if (st == nil)

    {

        st = [[Student alloc]init];

    }

    return st;

}


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

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

{

    /*

     关于 @synchronized(self)

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

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

     */

    

    @synchronized(self)

    {

        if (st == nil)

        {

            st = [super allocWithZone:zone];

        }

    }

    return st;

}

//防止copy产生新的对象

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

//-(id)copyWithZone:(NSZone *)zone

//{

//    return self;

//}


@end

=============================================================

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值