12.24

Java设计模式之单例模式

单例模式总结

单例模式使用场景

== 需要频繁地进行创建和销毁对象,创建对象时过多或耗费资源过多(即:重量级对象),但又经常用到的对象、工具类对象、频繁访问数据库或文件的对象(比如数据库,session工厂等)==


  • 饿汉式(静态常量)
  • 饿汉式(静态代码块)
  • 懒汉式(线程不安全)
  • 懒汉式(线程安全,同步方法)
  • 懒汉式(线程安全,同步代码块)
  • 双重检查
  • 静态内部类
  • 枚举

package singleton;

/**
 * @Author:wmy
 * @Date:2019/12/14
 * @Description:   饿汉式单例设计模式(静态变量)
 **/
class Singleton1 {
  /*
  *  在类的内部可以访问私有结构,所以可以在类的内部产生实例化对象
  * */
    private static Singleton1 instance = new Singleton1();
    private Singleton1(){

    }

    public static Singleton1 getInstance(){

        return instance;

    }

}


package singleton;

/**
 * @Author:wmy
 * @Date:2019/12/14
 * @Description: 饿汉式单例设计模式(静态代码块)
 **/
class Singleton1 {
    /*
    *  在类的内部可以访问私有结构,所以可以在类的内部产生实例化对象
    * */
    private static Singleton1 instance;

    private Singleton1() {

    }

    static {

        instance = new Singleton1();
    }

    public static Singleton1 getInstance() {

        return instance;

    }

}

package singleton;

/**
 * @Author:wmy
 * @Date:2019/12/14
 * @Description: 懒汉式单例设计模式(线程不安全)
 **/
class Singleton1 {

    private static Singleton1 instance;

    private Singleton1() {

    }



    public static Singleton1 getInstance() {
        if(instance==null){
            instance = new Singleton1();
        }
        return instance;

    }

}


package singleton;

/**
 * @Author:wmy
 * @Date:2019/12/14
 * @Description: 懒汉式单例设计模式(线程安全,同步方法)
 **/
class Singleton1 {

    private static Singleton1 instance;

    private Singleton1() {

    }



    public static synchronized Singleton1 getInstance() {
        if(instance==null){
            instance = new Singleton1();
        }
        return instance;

    }

}

package singleton;

import jnr.ffi.annotations.Synchronized;

/**
 * @Author:wmy
 * @Date:2019/12/14
 * @Description:   双重锁机制
 **/
class Singleton2 {
     private static volatile Singleton2 instance = null;

     private Singleton2(){

     }
    public static Singleton2 getInstance(){
         if(instance==null){
              synchronized(Singleton2.class) {
                 if(instance==null){
                     instance = new Singleton2();
                 }

             }

         }
         return instance;
    }
}

package singleton;

/**
 * @Author:wmy
 * @Date:2019/12/24
 * @Description:   枚举类型
 **/
public enum Singleton3 {
    INSTANCE;
    public void sayHello(){


        System.out.println("hello");
    }


}



设计模式之简单工厂模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值