设计模式之单例、多例模式
来源:互联网 发布:淘宝怎么删掉评价 编辑:程序博客网 时间:2024/06/15 06:46
单例设计模式只提供一个全局对象
饿汉式
public class NormalSingleton {
private static NormalSingleton s = new NormalSingleton();private NormalSingleton(){}
public static NormalSingleton getInstance(){
return s;
}
}
懒汉式
public class LazySingleton {
private static LazySingleton s = null;
private LazySingleton(){}
public static synchronized LazySingleton getInstance(){
if(s==null){
s = new LazySingleton();
}
return s;
}
}
多例模式
public class Multileton {
private static final int N = 10;
private static List<Multileton> l = new ArrayList<Multileton>(N);
//对象的序号
private int no;
private Multileton(int no){
this.no = no;
System.out.println("Create ["+ no +"] instance");
}
static{
for(int i = 0; i<N;i++ ){
l.add(new Multileton(i));
}
}
public static Multileton getRondomInstance(){
int num = (int)(Math.random()*N);
return l.get(num);
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
}
测试
public class MainApp {
public static void main(String[] args) {
// NormalSingleton s1 = NormalSingleton.getInstance();
// NormalSingleton s2 = NormalSingleton.getInstance();
// System.out.println(s1==s2);
// LazySingleton s1 = LazySingleton.getInstance();
// LazySingleton s2 = LazySingleton.getInstance();
// System.out.println(s1==s2);
Multileton ml1 = Multileton.getRondomInstance();
Multileton ml2 = Multileton.getRondomInstance();
System.out.println(ml1==ml2);
}
}
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之-单例设计模式
- php设计模式之单例、多例设计模式
- 设计模式之单例设计模式 标签: 设计模式
- 设计模式之单例
- 设计模式之单例
- Linux(Centos6.5)下安装svn服务器,并通过http访问
- 如何处理Tableview中cell的单选问题
- Unity学习笔记(2) --- Unity脚本的生命周期
- poj3273
- cocos2d-x v2 和 v3 对照手册
- 设计模式之单例、多例模式
- unity 延时调用方法
- mysql命令
- python2.7.10
- 修改数据库名 -----表名 ------属性名等
- 大话设计模式_桥接模式c++实现
- ShareSDK集成登陆功能
- [BZOJ1231] [Usaco2008 Nov]mixup2 混乱的奶牛
- 115 html IE9的a标签嵌套问题