单例模式的多种实现

单例模式的详情请关注《陈词滥调的单例》

#饿汉式(立即加载)

package com.zuoyang.singleton;

/**
 * 饿汉式:
 *  * 线程安全,在线程还出现以前就是创建了对象
 *
 */
public class SingLetonHungry  {
    private static  SingLetonHungry singLetonHungry = new SingLetonHungry();
   private SingLetonHungry(){}
   public static SingLetonHungry getInstance(){
       return singLetonHungry;
   }
}

###线程类

package com.zuoyang.singleton;

public class SingLetonHungryThread extends Thread {
    @Override
    public void run(){
 //        通过打印类的hashCode来确定是否为一个对象
        System.out.println(SingLetonHungry.getInstance().hashCode());
    }
}

###运行类

package com.zuoyang.singleton;

public class SingLetonHungryRun {
    public static void main(String[] args) {
        SingLetonHungryThread singLetonHungryThread1 = new SingLetonHungryThread();
        SingLetonHungryThread singLetonHungryThread2 = new SingLetonHungryThread();
        SingLetonHungryThread singLetonHungryThread3 = new SingLetonHungryThread();
        singLetonHungryThread1.start();
        singLetonHungryThread2.start();
        singLetonHungryThread3.start();
    }
}

###运行结果
[外链图片转存失败(img-xaLy3mdv-1563808031426)( https://uploader.shimo.im/f/UtBoMWPlgToCtr3n.png)]
#懒汉式(延迟加载)

##线程不安全版

package com.zuoyang.singleton;

/**
 *  懒汉式单例,但是多线程的情况下不安全
 */
public class SinLetonLazyOne {
    //静态块,公共内存区域
    private static SinLetonLazyOne sinLetonLazyOne;

    private SinLetonLazyOne(){
    }
    //调用方法之前,先判断
    //如果没有初始化,将其进行初始化,并且赋值
    //将该实例缓存好
    public static SinLetonLazyOne getInstance(){
        if (sinLetonLazyOne!=null) {

        }else {
            //两个线程都会进入这个if里面
             sinLetonLazyOne = new SinLetonLazyOne();
        }
        //如果已经初始化,直接返回之前已经保存好的结果
        return sinLetonLazyOne;
    }
}

###线程类

package com.zuoyang.singleton;

public class SinLetonlLazyOneThread extends Thread {

    @Override
    public void run(){
        System.out.println(SinLetonLazyOne.getInstance().hashCode());
    }
}

###运行类

package com.zuoyang.singleton;

public class SinLetonlLazyOneRun {
    public static void main(String[] args) {
        SinLetonlLazyOneThread sinLetonlLazyOneThread1 = new SinLetonlLazyOneThread();
        SinLetonlLazyOneThread sinLetonlLazyOneThread2 = new SinLetonlLazyOneThread();
        SinLetonlLazyOneThread sinLetonlLazyOneThread3 = new SinLetonlLazyOneThread();
        sinLetonlLazyOneThread1.start();
        sinLetonlLazyOneThread2.start();
        sinLetonlLazyOneThread3.start();
    }
}

###运行结果

##synchronized关键字版

package com.zuoyang.singleton;

/**
 * 基于加锁的线程安全的懒汉式单例
 */
public class SinLetonLazyTwo {

    private static SinLetonLazyTwo sinLetonLazyTwo;

    private SinLetonLazyTwo() {
    }

    //加锁 来保证多线程的情况下也是一个单例
    synchronized public static SinLetonLazyTwo getInstance() {
        try {
            if (sinLetonLazyTwo != null) {
            } else {
                Thread.sleep(3000);
                sinLetonLazyTwo = new SinLetonLazyTwo();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return sinLetonLazyTwo;
    }
}

###线程类

package com.zuoyang.singleton;

public class SinLetonlLazyTwoThread extends Thread {

    @Override
    public void run(){
        System.out.println(SinLetonLazyTwo.getInstance().hashCode());
    }
}

###运行类

package com.zuoyang.singleton;

public class SinLetonlLazyTwoRun {
    public static void main(String[] args) {
        SinLetonlLazyTwoThread sinLetonlLazyTwoThread1 = new SinLetonlLazyTwoThread();
        SinLetonlLazyTwoThread sinLetonlLazyTwoThread2 = new SinLetonlLazyTwoThread();
        SinLetonlLazyTwoThread sinLetonlLazyTwoThread3 = new SinLetonlLazyTwoThread();
        sinLetonlLazyTwoThread1.start();
        sinLetonlLazyTwoThread2.start();
        sinLetonlLazyTwoThread3.start();
    }
}

###运行结果

###同步代码块版(线程不安全)

package com.zuoyang.singleton;

/**
 * 基于加锁的线程不安全的懒汉式单例
 */
public class SinLetonLazyTwoTwo {

    private static SinLetonLazyTwoTwo sinLetonLazyTwoOne;

    private SinLetonLazyTwoTwo() {
    }

    //加锁 来保证多线程的情况下也是一个单例

    public static SinLetonLazyTwoTwo getInstance() {
        try {

            if (sinLetonLazyTwoOne != null) {
            } else {
                Thread.sleep(3000);
                synchronized (SinLetonLazyTwoTwo.class) {
                    sinLetonLazyTwoOne = new SinLetonLazyTwoTwo();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return sinLetonLazyTwoOne;
    }
}

###线程类

package com.zuoyang.singleton;

public class SinLetonlLazyTwoOneThread extends Thread {

    @Override
    public void run(){
        System.out.println(SinLetonLazyTwoOne.getInstance().hashCode());
    }
}

###运行类

package com.zuoyang.singleton;

public class SinLetonlLazyTwoTwoRun {
    public static void main(String[] args) {
        SinLetonlLazyTwoTwoThread sinLetonlLazyTwoTwoThread1 = new SinLetonlLazyTwoTwoThread();
        SinLetonlLazyTwoTwoThread sinLetonlLazyTwoTwoThread2 = new SinLetonlLazyTwoTwoThread();
        SinLetonlLazyTwoTwoThread sinLetonlLazyTwoTwoThread3 = new SinLetonlLazyTwoTwoThread();
        sinLetonlLazyTwoTwoThread1.start();
        sinLetonlLazyTwoTwoThread2.start();
        sinLetonlLazyTwoTwoThread3.start();
    }
}

###运行结果

###DCL双检查锁机制版(Double-Check Locking)

package com.zuoyang.singleton;

/**
 * 基于双重检查锁的机制实现的单例模式
 */
public class SinLetonLazyThree {

    private static SinLetonLazyThree sinLetonLazyTwoOne;

    private SinLetonLazyThree() {
    }


    public static SinLetonLazyThree getInstance() {
        try {
//存在多个线程,跑进来在这里
            if (sinLetonLazyTwoOne != null) {
            } else {
                Thread.sleep(3000);
                //后面进来的线程需要判断lazy是否已经初始化了,不然的话,会重新创建新的对象
                synchronized (SinLetonLazyThree.class) {
                    if (sinLetonLazyTwoOne == null)
                        sinLetonLazyTwoOne = new SinLetonLazyThree();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return sinLetonLazyTwoOne;
    }
}

###线程类

package com.zuoyang.singleton;

public class SinLetonlLazyThreeThread extends Thread {

    @Override
    public void run(){
        System.out.println(SinLetonLazyThree.getInstance().hashCode());
    }
}

###运行类

package com.zuoyang.singleton;

public class SinLetonlLazyThreeRun {
    public static void main(String[] args) {
        SinLetonlLazyThreeThread sinLetonlLazyThreeThread1 = new SinLetonlLazyThreeThread();
        SinLetonlLazyThreeThread sinLetonlLazyThreeThread2 = new SinLetonlLazyThreeThread();
        SinLetonlLazyThreeThread sinLetonlLazyThreeThread3 = new SinLetonlLazyThreeThread();
        sinLetonlLazyThreeThread1.start();
        sinLetonlLazyThreeThread2.start();
        sinLetonlLazyThreeThread3.start();
    }
}

###运行结果

#使用静态内部类实现单例模式

package com.zuoyang.singleton;

public class SingLetonStatic {
    private static  SingLetonStatic singLetonStatic =null;

    private SingLetonStatic(){}

    static {
        singLetonStatic = new SingLetonStatic();
    }

    public static SingLetonStatic getInstance() {
        return singLetonStatic;
    }
}

###线程类

package com.zuoyang.singleton;

public class SingLetonStaticThread extends Thread{
    @Override
    public void run(){
        for (int i = 0; i <5 ; i++) {
            System.out.println(SingLetonStatic.getInstance().hashCode());
        }
    }
}

###运行类

package com.zuoyang.singleton;

public class SingLetonStaticRun {
    public static void main(String[] args) {
        SingLetonStaticThread singLetonStaticThread1 = new SingLetonStaticThread();
        SingLetonStaticThread singLetonStaticThread2 = new SingLetonStaticThread();
        SingLetonStaticThread singLetonStaticThread3 = new SingLetonStaticThread();
        singLetonStaticThread1.start();
        singLetonStaticThread2.start();
        singLetonStaticThread3.start();
    }
}

###运行结果

#序列化与反序列化的单例模式

package com.zuoyang.singleton;

import java.io.Serializable;

public class SingLetonSerializable implements Serializable {

    private SingLetonSerializable(){}

    private static class SingLetonSerializableHandler{
        private static final SingLetonSerializable singLetonSerializable  = new SingLetonSerializable();
    }

    public static SingLetonSerializable getInstance(){
        return SingLetonSerializableHandler.singLetonSerializable;
    }

    protected Object readResolve(){
        return SingLetonSerializableHandler.singLetonSerializable;
    }
}

###运行类

package com.zuoyang.singleton;

import java.io.*;

public class SingLetonSerializableSaveAndRead {
    public static void main(String[] args) {
        try {
            SingLetonSerializable singLetonSerializable = SingLetonSerializable.getInstance();
            FileOutputStream fileOutputStream = new FileOutputStream(new File("E://MyOne.txt"));
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(singLetonSerializable);
            objectOutputStream.close();
            fileOutputStream.close();
            System.out.println(singLetonSerializable.hashCode());
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(new File("E://MyOne.txt"));
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            SingLetonSerializable singLetonSerializable = (SingLetonSerializable)objectInputStream.readObject();
            objectInputStream.close();
            fileInputStream.close();
            System.out.println(singLetonSerializable.hashCode());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}

###运行结果

#enum枚举实现单例模式

package com.zuoyang.singleton;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SingLetonEumOne {
    public enum SingLetonEumTest {
        connectionFactory;
        private Connection connection;
        private SingLetonEumTest(){
            try {
                Class.forName("com.mysql.jdbc.Driver");
                String url="jdbc:mysql://localhost:3306";
                String user="root";
                String password="root";
                connection = DriverManager.getConnection(url,user,password);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        public Connection getConnection(){
            return connection;
        }
    }
    public static Connection getConnection(){
        return SingLetonEumTest.connectionFactory.getConnection();
    }
}

###线程类

package com.zuoyang.singleton;

public class SingLetonEumThreadTest extends Thread {
    @Override
    public void run(){
        for (int i = 0; i <5 ; i++) {
            System.out.println(SingLetonEumOne.getConnection().hashCode());
        }

    }
}

###运行类

package com.zuoyang.singleton;

public class SingLetonEumRunTest {
    public static void main(String[] args) {
        SingLetonEumThreadTest singLetonEumThreadTest1 = new SingLetonEumThreadTest();
        SingLetonEumThreadTest singLetonEumThreadTest2 = new SingLetonEumThreadTest();
        SingLetonEumThreadTest singLetonEumThreadTest3 = new SingLetonEumThreadTest();
        singLetonEumThreadTest1.start();
        singLetonEumThreadTest2.start();
        singLetonEumThreadTest3.start();
    }
}

###运行结果

#GitHub地址

https://github.com/dxf1998/singleton.git
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值