1、java版java
單例類 Singleton.java :ios
public class Singleton { private static Singleton instance = null; private Singleton(){ } public static Singleton getInstance(){ if(instance == null){ instance = new Singleton(); } return instance; } }
測試類 Test.java :c++
public class Test { public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); System.out.println(singleton); Singleton singleton2 = Singleton.getInstance(); System.out.println(singleton2); } }
測試結果:objective-c
com.hejinlai.singleton.Singleton@6345e044ide
com.hejinlai.singleton.Singleton@6345e044測試
2、c++版spa
單例類 Singleton.h Singleton.cpp :get
// // Singleton.h // Pattern // // Created by hejinlai on 13-8-6. // Copyright (c) 2013年 yunzhisheng. All rights reserved. // #ifndef __Pattern__Singleton__ #define __Pattern__Singleton__ #include <iostream> class Singleton { public: static Singleton * getInstance(); private: Singleton(); static Singleton * instance; }; #endif /* defined(__Pattern__Singleton__) */
// // Singleton.cpp // Pattern // // Created by hejinlai on 13-8-6. // Copyright (c) 2013年 yunzhisheng. All rights reserved. // #include "Singleton.h" Singleton * Singleton::instance = NULL; Singleton::Singleton() { } Singleton * Singleton::getInstance() { if (instance == NULL) { instance = new Singleton(); } return instance; }
測試 main.cpp :it
// // main.cpp // Pattern // // Created by hejinlai on 13-8-6. // Copyright (c) 2013年 yunzhisheng. All rights reserved. // #include <iostream> #include "Singleton.h" using namespace std; int main(int argc, const char * argv[]) { Singleton * singleton = Singleton::getInstance(); cout << singleton << endl; Singleton * singleton2 = Singleton::getInstance(); cout << singleton2 << endl; return 0; }
測試結果:io
0x1001000e0
0x1001000e0
3、objective-c 版
單例類 Singleton.h Singleton.m :
// // Singleton.h // ObcPattern // // Created by hejinlai on 13-8-6. // Copyright (c) 2013年 yunzhisheng. All rights reserved. // #import <Foundation/Foundation.h> @interface Singleton : NSObject +(Singleton *)getInstance; @end
// // Singleton.m // ObcPattern // // Created by hejinlai on 13-8-6. // Copyright (c) 2013年 yunzhisheng. All rights reserved. // #import "Singleton.h" static Singleton *instance = nil; @implementation Singleton +(Singleton *)getInstance { if (instance == nil) { instance = [[self alloc] init]; } return instance; } @end
測試 main.m :
// // main.m // ObcPattern // // Created by hejinlai on 13-8-6. // Copyright (c) 2013年 yunzhisheng. All rights reserved. // #import <Foundation/Foundation.h> #import "Singleton.h" int main(int argc, const char * argv[]) { @autoreleasepool { Singleton *singleton = [Singleton getInstance]; NSLog(@"%@", singleton); Singleton *singleton2 = [Singleton getInstance]; NSLog(@"%@", singleton2); } return 0; }
測試結果:
2013-08-06 19:43:16.073 ObcPattern[8094:303] <Singleton: 0x1001098b0>
2013-08-06 19:43:16.075 ObcPattern[8094:303] <Singleton: 0x1001098b0>