Python 官方文档:入门教程 => 点击学习
目录一、单例模式二、写法三、饿汉式四、懒汉式五、内部类六、枚举七、结论一、单例模式 属于创建者模式的一种, 单例模式的目的是使该类只有一个实例,同一个类的不同对象有不同的hashCo
属于创建者模式的一种, 单例模式的目的是使该类只有一个实例,同一个类的不同对象有不同的hashCode()
单例模式是由该类自行创建唯一个向外暴露的全局的对象
public class SingleTest{
public static void main(String[] args) {
Single single1 = Single.getInstance();
Single single2 = Single.getInstance();
System.out.println(single1.hashCode());
System.out.println(single2.hashCode());
System.out.println(single1 == single2);
}
}
class Single {
final static Single INSTANCE = new Single();
public static Single getInstance(){return INSTANCE;}
}
//懒汉式的线程安全的写法又称为双检索懒汉模式
public class SingleTest {
public static void main(String[] args) {
for(int i = 0;i < 10; i++){
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Single.getInstance().hashCode());
}
}).start();
}
}
}
class Single{
private static Single instance = null;
Single(){}
public static Single getInstance(){
if (instance == null){
synchronized (Single.class) {
if(instance == null){
try{
Thread.sleep(1);
}catch (Exception e){
e.printStackTrace();
}
instance = new Single();
}
}
}
return instance;
}
}
public class SingleTest {
public static void main(String[] args) {
Single single1 = Single.getInstance();
Single single2 = Single.getInstance();
System.out.println(single1.hashCode());
System.out.println(single2.hashCode());
System.out.println(single1 == single2);
}
}
class Single{
private static Single instance;
public static Single getInstance(){
return InnerSingle.INSTANCE;
}
private static class InnerSingle{
private final static Single INSTANCE = new Single();
}
}
//枚举:完美写法
public class SingleTest {
public static void main(String[] args) {
Single single1 = Single.INSTANCE;
Single single2 = Single.INSTANCE;
System.out.println(single1.hashCode());
System.out.println(single2.hashCode());
System.out.println(single1 == single2);
}
}
enum Single{
INSTANCE;
}
优点:
缺点:
到此这篇关于简单总结单例模式的4种写法的文章就介绍到这了,更多相关单例模式的4种写法内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 简单总结单例模式的4种写法
本文链接: https://lsjlt.com/news/127842.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0