美文网首页
设计模式的多种实现

设计模式的多种实现

作者: 左羊 | 来源:发表于2019-07-22 23:13 被阅读0次

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

    饿汉式(立即加载)

    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();
        }
    }
    

    运行结果

    [图片上传失败...(image-3f198-1563808417878)]

    懒汉式(延迟加载)

    线程不安全版

    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();
        }
    }
    

    运行结果

    [图片上传失败...(image-f13f59-1563808417878)]

    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();
        }
    }
    

    运行结果

    [图片上传失败...(image-fddb4a-1563808417878)]

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

    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();
        }
    }
    

    运行结果

    [图片上传失败...(image-e2a319-1563808417878)]

    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();
        }
    }
    

    运行结果

    [图片上传失败...(image-63ced0-1563808417878)]

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

    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();
        }
    }
    

    运行结果

    [图片上传失败...(image-15f231-1563808417878)]

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

    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();
            }
    
        }
    }
    

    运行结果

    [图片上传失败...(image-67ac5a-1563808417878)]

    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();
        }
    }
    

    运行结果

    [图片上传失败...(image-70c9ae-1563808417878)]

    GitHub地址

    https://github.com/dxf1998/singleton.git
    

    相关文章

      网友评论

          本文标题:设计模式的多种实现

          本文链接:https://www.haomeiwen.com/subject/xstnlctx.html