首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java常用设计模式-单例模式(Singleton Pattern)

Java常用设计模式-单例模式(Singleton Pattern)

作者头像
gang_luo
发布2020-08-13 11:36:46
2440
发布2020-08-13 11:36:46
举报
文章被收录于专栏:gang_luogang_luogang_luo

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式

特点:

  1. 单例类只能有一个实例。
  2. 单例类必须自己创建自己的唯一实例。
  3. 单例类必须给所有其他对象提供这一实例

懒汉式:

package com.example;

/**
 * 懒汉式
 * 加锁 synchronized线程安全
 */
public class Student {

    private static Student student;

    private Student(){};

    public static synchronized Student getInstance(){
        if (student == null) {
            student = new Student();
        }
        return student;
    }

    public static void main(String[] args) {
        Student student1 = Student.getInstance();
        Student student2 = Student.getInstance();
        if(student1 == student2){
            System.out.println("同一个学生");
        }else{
            System.out.println("不是同一个学生");
        }
    }
}

输出结果:

饿汉式:

package com.example;

/**
 * 饿汉式
 * 多线程安全
 * 类加载时就初始化
 */
public class Student1 {

    private static Student1 student1 = new Student1();

    private Student1(){};

    public static synchronized Student1 getInstance(){
        return student1;
    }

    public static void main(String[] args) {
        Student1 student1 = Student1.getInstance();
        Student1 student2 = Student1.getInstance();
        if(student1 == student2){
            System.out.println("同一个学生");
        }else{
            System.out.println("不是同一个学生");
        }
    }
}

输出结果:

双重校验锁

package com.example;

/**
 * 双重校验锁
 * 线程安全
 */
public class Student2 {

    private volatile static Student2 student2;
    private Student2 (){}
    public static Student2 getInstance() {
        if (student2 == null) {
            synchronized (Student2.class) {
                if (student2 == null) {
                    student2 = new Student2();
                }
            }
        }
        return student2;
    }

    public static void main(String[] args) {
        Student2 student1 = Student2.getInstance();
        Student2 student2 = Student2.getInstance();
        if(student1 == student2){
            System.out.println("同一个学生");
        }else{
            System.out.println("不是同一个学生");
        }
    }
}

输出结果:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-04-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档