单例模式:恶汉式,懒汉式,双重锁,静态内部类,枚举
1.恶汉式{
//构造方法私有化
private HttpManager(){}
//自行实例化
public static HttpManager httpManager = new HttpManager();
//提供公共方法
public static HttpManager getInstance(){
return httpManager;
}
//设置内容
public void getString(){
Log.i("--s","123");
}
}
2.懒汉式{
//构造方法私有化
private HttpManager(){}
//自行实例化
public static HttpManager httpManager = null;
//提供公共方法
public static HttpManager getInstance(){
if(httpManager==null){
httpManager = new HttpManager();
}
return httpManager;
}
//设置内容
public void getString(){
Log.i("--s","123");
}
}
3.双重锁{
private HttpManager(){}
private static volatile HttpManager httpManager = null;
public static HttpManager getInstance(){
if(httpManager==null){
synchronized (HttpManager.class){
if(httpManager==null){
httpManager = new HttpManager();
}
}
}
return httpManager;
}
}
4.案例
1.GET请求获取字符串
1.1布局{
![](https://i-blog.csdnimg.cn/blog_migrate/a065a152bdb587ea6a088c2f2fcf342b.png)
}
1.2 MyActicity{
![](https://i-blog.csdnimg.cn/blog_migrate/ed94ae9cf4625a36f97c8c564fe175b3.png)
![](https://i-blog.csdnimg.cn/blog_migrate/a582b31c591a357d973cf1cff7b716a2.png)
}
1.3 创建类使用单例模式
![](https://i-blog.csdnimg.cn/blog_migrate/168b052fcabcedbe65e314a38c653301.png)
1.4效果
![](https://i-blog.csdnimg.cn/blog_migrate/f06b4d7188d69ce6e4ccb36194d0c22e.png)
2.POST请求获取数据
2.1布局
![](https://i-blog.csdnimg.cn/blog_migrate/e5eaad64e45bc724b011e7060ca76fe4.png)
2.2MyActicity
![](https://i-blog.csdnimg.cn/blog_migrate/3c2f920133d674ba29deca0feebfa31c.png)
2.3单例模式
![](https://i-blog.csdnimg.cn/blog_migrate/f5196642d37e93c2f4a3e35c91785339.png)
2.4效果
![](https://i-blog.csdnimg.cn/blog_migrate/ce282a3b92570a8c07d66c84f64c358f.png)
注:
判断是否为第一次
![](https://i-blog.csdnimg.cn/blog_migrate/0cd46eaa2974a37d9e43eadeb6b845a6.png)
2.POST要使用输出流
![](https://i-blog.csdnimg.cn/blog_migrate/3363a0c4c1e5d3d8452ed8f774911c32.png)
链接后面所需要的值
![](https://i-blog.csdnimg.cn/blog_migrate/1bc7f9fb5eb350fcc89d43adc2c1cfd4.png)