首先我们来看下单例模式的定义:
定义:在整个应用中,保证一个类只有一个实例,它提供了一个可以访问到它自己的全局访问点(静态方法)。
单例模式中有区分了懒汉式和饿汉式,懒汉式主要是用时间来换空间,饿汉式则是用空间来换时间。饿汉式是线程安全的,懒汉式是非线程安全的,如果要实现懒汉式的非线程安全,则可以再访问点添加synchronized关键字声明即可。在其他的一些项目中还使用了双重检测枷锁机制。
现在我们来看下代码,我会提供代码下载供大家参考。
AndroidManifest.xml文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yangfuhai.singleton"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".SingletonActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
注意添加:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
用于访问网络
activity代码 SingletonActivity
package com.yangfuhai.singleton;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
/**
* @title 单例模式
* @description 单例模式
* @company 探索者网络工作室(www.tsz.net)
* @author michael Young (www.YangFuhai.com)
* @version 1.0
* @created 2012-8-19
*/
public class SingletonActivity extends Activity {
TextView mTv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTv = (TextView) findViewById(R.id.textView);
mTv.setText("正在加载www.devchina.com数据。。。");
new Thread(new Runnable() {
@Override
public void run() {
final String strContext = HttpUtils.get().getUrlContext("http://www.devchina.com");
runOnUiThread(new Runnable() {
@Override
public void run() {
if(strContext!=null)
mTv.setText(strContext);
else
mTv.setText("加载失败。。。");
}
});
}
}).start();
}
}
http访问网络代码HttpUtils,用单例模式实现
package com.yangfuhai.singleton;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.util.Log;
/**
* @title Http请求工具类
* @description 请求http数据,单例模式
* @company 探索者网络工作室(www.tsz.net)
* @author michael Young (www.YangFuhai.com)
* @version 1.0
* @created 2012-8-19
*/
public class HttpUtils {
private static final String DEBUG_TAG = "HttpUtils";
private HttpUtils() {} //单例模式中,封闭创建实例接口
private static HttpUtils httpUtils = null;
//提供了一个可以访问到它自己的全局访问点
public static HttpUtils get(){
if(httpUtils == null)
httpUtils = new HttpUtils();
return httpUtils;
}
/**
* 获取某个url的内容
* @param strUrl
* @return
*/
public String getUrlContext(String strUrl){
InputStream is = null;
int len = 500;
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
//这里指获取了500(len=500)字节,如果想
//整个网页全部获取可以用conn.getContentLength()来代替len
String contentAsString = readInputStream(is, len);
return contentAsString;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 读取 InputStream 内容
* @param stream
* @param len
* @return
* @throws IOException
* @throws UnsupportedEncodingException
*/
public String readInputStream(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
![](https://img-my.csdn.net/uploads/201208/19/1345371159_7919.png)
源码下载地址:
http://download.csdn.net/detail/michael_yy/4511109
大家多多指教,转载请注明来之 www.devchina.com 或者 csdn, 谢谢。
谢谢大家关注,我继续在博客中讲解了经典的23中模式中在android实际项目中灵活运用,下一篇 《Android也架构之三:简单工厂模式优化网络请求》敬请关注。