单例,单例形式

单态

单例,单例格局

#import "NSObjectGCDAsyncSocket.h"

@implementation NSObjectGCDAsyncSocket
{
    GCDAsyncSocket* socket;
}
/**
 *  单例
 *
 *  @return
 */
+(NSObjectGCDAsyncSocket *)defaultSocket
{
    //socket只会实例化一次
    static NSObjectGCDAsyncSocket* socket=nil;
    //保证线程安全,defaultSocket只执行一次
    static dispatch_once_t once;
    dispatch_once(&once, ^
    {
        socket=[[NSObjectGCDAsyncSocket alloc] init];
    });
    return socket;
}

/**
 *  初始化
 *
 *
 *  @return self
 */
-(instancetype)init
{
    self=[super init];
    if (self)
    {
        socket=[[GCDAsyncSocket alloc] initWithDelegate:self
                                          delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    }
    return self;
}

http://www.bkjia.com/IOSjc/1070625.htmlwww.bkjia.comtruehttp://www.bkjia.com/IOSjc/1070625.htmlTechArticle单例,单例模式 #import
“NSObjectGCDAsyncSocket.h”@implementation NSObjectGCDAsyncSocket{
GCDAsyncSocket* socket;}/** * 单例 * * @return
*/+(NSObjectGCDAsyncSocket * )defau…

 1 <?php 
 2 //单例
 3 class Db{
 4     //创建静态私有的变量保存该类对象
 5     static private $instance;
 6     //参数
 7     static private $config;
 8     //防止直接创建对象
 9     private function __construct($config){
10         self::$config = $config;
11         echo 'new obj';
12     }
13     //防止克隆对象
14     private function __clone(){
15         return false;
16     }
17     static public function getInstance($config){
18         //判断$instance是否是Uni的对象
19         if (!self::$instance instanceof self) {
20             //没有则创建
21             self::$instance = new static($config);
22         }
23         return self::$instance;
24         
25     }
26     public function getConfig(){
27         return $this -> config;
28     }
29 }
30 $data = Db::getInstance(1);
31 var_dump($data -> getConfig());
32 ?>

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图