我是靠谱客的博主 发嗲方盒,这篇文章主要介绍设计模式之单例模式,现在分享给大家,希望可以做个参考。

单例模式又叫singleTon模式,单例模式分三种:懒汉式单例、饿汉式单例、登记式单例三种。
  单例模式有一下特点:
  1、单例类只能有一个实例。
  2、单例类必须自己创建自己的唯一实例。
  3、单例类必须给所有其他对象提供这一实例。
先来看一下单线程下的单例模式:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Test { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } //该类只能有一个实例 private Test(){} //私有无参构造方法 //该类必须自行创建 //有2种方式 /*private static final Test ts=new Test();*/ private static Test ts1=null; //这个类必须自动向整个系统提供这个实例对象 public static Test getTest(){ if(ts1==null){ ts1=new Test(); } return ts1; } public void getInfo(){ System.out.println("output message "+name); } }

这就是一个单例模式,只是并不是线程安全的。
下面我们来看看经典的单例模式:

1、饿汉式

复制代码
1
2
3
4
5
6
7
8
9
10
11
//饿汉式单例类.在类初始化时,已经自行实例化 public class Singleton1 { //私有的默认构造子 private Singleton1() {} //已经自行实例化 private static final Singleton1 single = new Singleton1(); //静态工厂方法 public static Singleton1 getInstance() { return single; } }

2、懒汉式

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//懒汉式单例类.在第一次调用的时候实例化 public class Singleton2 { //私有的默认构造子 private Singleton2() {} //注意,这里没有final private static Singleton2 single=null; //静态工厂方法 public synchronized static Singleton2 getInstance() { if (single == null) { single = new Singleton2(); } return single; } }

3、登记式

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.HashMap; import java.util.Map; //登记式单例类. //类似Spring里面的方法,将类名注册,下次从里面直接获取。 public class Singleton3 { private static Map<String,Singleton3> map = new HashMap<String,Singleton3>(); static{ Singleton3 single = new Singleton3(); map.put(single.getClass().getName(), single); } //保护的默认构造子 protected Singleton3(){} //静态工厂方法,返还此类惟一的实例 public static Singleton3 getInstance(String name) { if(name == null) { name = Singleton3.class.getName(); System.out.println("name == null"+"--->name="+name); } if(map.get(name) == null) { try { map.put(name, (Singleton3) Class.forName(name).newInstance()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return map.get(name); } //一个示意性的商业方法 public String about() { return "Hello, I am RegSingleton."; } public static void main(String[] args) { Singleton3 single3 = Singleton3.getInstance(null); System.out.println(single3.about()); } }

摘抄自火星十一郎-张朋飞

最后

以上就是发嗲方盒最近收集整理的关于设计模式之单例模式的全部内容,更多相关设计模式之单例模式内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(89)

评论列表共有 0 条评论

立即
投稿
返回
顶部