单例设计模式小结

来源:互联网 发布:淘宝刷单兼职hao360 编辑:程序博客网 时间:2024/05/16 23:57
单例设计模式:
单例模式用途:保证类在内存中只有一个对象。

单例模式案例:
(1)饿汉式 开发用这种方式。
class Singleton {
//1,私有构造函数
private Singleton(){}
//2,创建本类对象
private static Singleton s = new Singleton();
//3,对外提供公共的访问方法
public static Singleton getInstance() {
return s;
}
}
(2)懒汉式 面试写这种方式。多线程的问题? 
class Singleton {
//1,私有构造函数
private Singleton(){}
//2,声明一个本类的引用
private static Singleton s;
//3,对外提供公共的访问方法
public static sychronized Singleton getInstance() {
if(s == null)
//线程1,线程2
s = new Singleton();
return s;
}
}
(3)第三种格式
class Singleton {
private Singleton() {
public static final Singleton s = new Singleton();//final是最终的意思,被final修饰的变量不可以被更改
}

JDK中单例模式应用:
Runtime类是一个单例类
Runtime r = Runtime.getRuntime();
r.exec("shutdown -s -t 300");//300秒后关机
r.exec("shutdown -a");//取消关机

数据结构的思想:
拿时间换空间 拿空间换时间
0 0
原创粉丝点击