單例模式 Singleton
保證一個類別只有一個物件,而且要提供存取該物件的統一方法
public class FragmentOne extends Fragment {
private static FragmentOne fragmentOne = null;
private Singleton(){
// 建立物件
}
public static FragmentOne getInstance() {
if (fragmentOne == null) {
// 多執行緒時,當物件需要被建立時才使用synchronized保證fragmentOne一定是單一的 ,增加程式校能
synchronized(FragmentOne.class){
if (fragmentOne == null) {
// 第一次被呼叫的時候再建立物件
fragmentOne = new FragmentOne();
}
}
return fragmentOne;
}
}
補充
package com.test;
public class TestSingletionPattern {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
class Singleton {
private static final Singleton singleton = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return singleton;
}
public static void doSomething() {
}
}
class SingletonB {
private static SingletonB singleton = new SingletonB();
private SingletonB() {
}
// 多執行緒時使用synchronized保證Singleton一定是單一的
public static synchronized SingletonB getInstance() {
if (singleton == null) {
singleton = new SingletonB();
}
return singleton;
}
public static void doSomething() {
}
}
class SingletonC {
private static SingletonC singleton = new SingletonC();
private SingletonC() {
}
// 多執行緒時,當物件需要被建立時才使用synchronized保證Singleton一定是單一的 ,增加程式校能
public static SingletonC getInstance() {
if (singleton == null) {
synchronized (SingletonC.class) {
if (singleton == null) {
singleton = new SingletonC();
}
}
}
return singleton;
}
public static void doSomething() {
}
}
沒有留言:
張貼留言