単例模式
2016-07-24 22:18
459 查看
public class SimpleTest {
// 饿汉模式
private SimpleTest(){
}
private static SimpleTest instance = new SimpleTest();
public static SimpleTest getinstance(){
return instance;
}
}
public class SimpleTest1 {
// 懒汉模式
private SimpleTest1(){
}
private static SimpleTest1 instance;
public static SimpleTest1 getInstance(){
if(instance == null){
instance = new SimpleTest1();
}
return instance;
}
}
//线程安全
private volatile static SimpleTest3 singleton;
private SimpleTest3(){
}
public static SimpleTest3 getInstance() {
if (singleton== null) {
synchronized (SimpleTest3.class) {
if (singleton== null) {
singleton= new SimpleTest3();
}
}
}
return singleton;
}
public class SimpleTest4 {
// 静态内部类单例模式
private SimpleTest4(){
}
public static SimpleTest4 getInstance(){
return SingletonHolder.sInstance;
}
private static class SingletonHolder {
private static final SimpleTest4 sInstance = new SimpleTest4();
}
}
//枚举单例的优点就是简单,但是大部分应用开发很少用枚举,可读性并不是很高,不建议用。
public enum SimpleTest5 {
INSTANCE;
public void doSomeThing() {
}
}
// 饿汉模式
private SimpleTest(){
}
private static SimpleTest instance = new SimpleTest();
public static SimpleTest getinstance(){
return instance;
}
}
public class SimpleTest1 {
// 懒汉模式
private SimpleTest1(){
}
private static SimpleTest1 instance;
public static SimpleTest1 getInstance(){
if(instance == null){
instance = new SimpleTest1();
}
return instance;
}
}
//线程安全
private volatile static SimpleTest3 singleton;
private SimpleTest3(){
}
public static SimpleTest3 getInstance() {
if (singleton== null) {
synchronized (SimpleTest3.class) {
if (singleton== null) {
singleton= new SimpleTest3();
}
}
}
return singleton;
}
public class SimpleTest4 {
// 静态内部类单例模式
private SimpleTest4(){
}
public static SimpleTest4 getInstance(){
return SingletonHolder.sInstance;
}
private static class SingletonHolder {
private static final SimpleTest4 sInstance = new SimpleTest4();
}
}
//枚举单例的优点就是简单,但是大部分应用开发很少用枚举,可读性并不是很高,不建议用。
public enum SimpleTest5 {
INSTANCE;
public void doSomeThing() {
}
}
相关文章推荐
- Java 使用对话框选择文件并输出到控制台
- iOS NSMapTable
- servlet生命周期
- 剑指Offer面试题8:寻找旋转数组的最小元素
- Unity项目优化
- 阅读笔记1
- 深入解析Java编程中方法的参数传递
- HTML——表格标记
- 博弈论合集
- maven安装
- 错题724-java
- Android热修复:Andfix和Hotfix,两种方案的比较与实现
- NOI2016 day1 总(xia)结(che)
- 汉诺塔
- LeetCode 237 Delete Node in a Linked List
- ecshop 后台设置模板时, 500错误
- CocosCreator入门Hello World
- JSTL标签总结
- 明细数据联查预算表 功能分析 个人总结
- String Manipulation