让class只有一个实例的例子

最近在学习android的webkit,看到一些自己认为是好的代码或者方式就把它记录下来,方便以后复习与借鉴。

WebViewDatabase是一个单实例对象,通过getInstance方法获取WebViewDatabase的实例。WebViewDatabase是WebKit模块中的内部对象,仅供WebKit框架内部使用。

private static WebViewDatabase mInstance = null;
private WebViewDatabase() {
		// Singleton only, use getInstance()
	}

public static synchronized WebViewDatabase getInstance(Context context) {
		if (mInstance == null) {
			mInstance = new WebViewDatabase();
			mDatabase = context.openOrCreateDatabase(DATABASE_FILE, 0, null);

			// mDatabase should not be null,
			// the only case is RequestAPI test has problem to create db
			if (mDatabase != null && mDatabase.getVersion() != DATABASE_VERSION) {
				mDatabase.beginTransaction();
				try {
					upgradeDatabase();
					mDatabase.setTransactionSuccessful();
				} finally {
					mDatabase.endTransaction();
				}
			}

			if (mDatabase != null) {
				// use per table Mutex lock, turn off database lock, this
				// improves performance as database's ReentrantLock is expansive
				mDatabase.setLockingEnabled(false);
			}

			mCacheDatabase = context.openOrCreateDatabase(CACHE_DATABASE_FILE,
					0, null);

			// mCacheDatabase should not be null,
			// the only case is RequestAPI test has problem to create db
			if (mCacheDatabase != null
					&& mCacheDatabase.getVersion() != CACHE_DATABASE_VERSION) {
				mCacheDatabase.beginTransaction();
				try {
					upgradeCacheDatabase();
					bootstrapCacheDatabase();
					mCacheDatabase.setTransactionSuccessful();
				} finally {
					mCacheDatabase.endTransaction();
				}
				// Erase the files from the file system in the
				// case that the database was updated and the
				// there were existing cache content
				CacheManager.removeAllCacheFiles();
			}

			if (mCacheDatabase != null) {
				// use InsertHelper for faster insertion
				mCacheInserter = new DatabaseUtils.InsertHelper(mCacheDatabase,
						"cache");
				mCacheUrlColIndex = mCacheInserter
						.getColumnIndex(CACHE_URL_COL);
				mCacheFilePathColIndex = mCacheInserter
						.getColumnIndex(CACHE_FILE_PATH_COL);
				mCacheLastModifyColIndex = mCacheInserter
						.getColumnIndex(CACHE_LAST_MODIFY_COL);
				mCacheETagColIndex = mCacheInserter
						.getColumnIndex(CACHE_ETAG_COL);
				mCacheExpiresColIndex = mCacheInserter
						.getColumnIndex(CACHE_EXPIRES_COL);
				mCacheMimeTypeColIndex = mCacheInserter
						.getColumnIndex(CACHE_MIMETYPE_COL);
				mCacheEncodingColIndex = mCacheInserter
						.getColumnIndex(CACHE_ENCODING_COL);
				mCacheHttpStatusColIndex = mCacheInserter
						.getColumnIndex(CACHE_HTTP_STATUS_COL);
				mCacheLocationColIndex = mCacheInserter
						.getColumnIndex(CACHE_LOCATION_COL);
				mCacheContentLengthColIndex = mCacheInserter
						.getColumnIndex(CACHE_CONTENTLENGTH_COL);
			}
		}

		return mInstance;
	}
WebViewDatabase db = WebViewDatabase.getInstance(this);

相关推荐