设计模式01(单例模式)

单例的7种实现

TYPE01-- 饿汉式(静态变量)

public class SingletonTest01 {

    public static void main(String[] args) {
        //测试
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Singleton instance = Singleton.getInstance();
                System.out.println(Thread.currentThread().getName() + "   instance.hashCode:" + instance.hashCode());
            }).start();
        }
    }
}

/**
 * @Author: my_code
 * @Description: 饿汉式(静态变量)
 * 在类加载的是创建
 * 缺点:存在内存浪费
 * @Date: Create in 21:15 2020/9/12
 */
class Singleton {
    //1.构造器私有化,外部能new
    private Singleton() {
    }

    //2.本类内部创建对象实例
    private final static Singleton instance = new Singleton();

    //3.提供一个公有的静态方法,返回实例对象
    public static Singleton getInstance() {
        return instance;
    }
}

TYPE02 – 饿汉式(静态代码块)

public class SingletonTest02 {

    public static void main(String[] args) {
        //测试
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Singleton instance = Singleton.getInstance();
                System.out.println(Thread.currentThread().getName() + "   instance.hashCode:" + instance.hashCode());
            }).start();
        }
    }
}

/**
 * @Author: my_code
 * @Description: 饿汉式(静态代码块)
 * 在类加载的是创建
 * 缺点:存在内存浪费
 * @Date: Create in 21:06 2020/9/12
 */
class Singleton {
    //1.构造器私有化,外部能new
    private Singleton() {
    }

    //2.本类内部创建对象实例
    private static Singleton instance;

    //3.在静态代码块中创建实例对象
    static {
        instance = new Singleton();
    }

    //4.提供一个公有的静态方法,返回实例对象
    public static Singleton getInstance() {
        return instance;
    }
}

TYPE03 – 懒汉式(线程不安全)

public class SingletonTest03 {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Singleton instance = Singleton.getInstance();
                System.out.println(Thread.currentThread().getName() + "   instance.hashCode:" + instance.hashCode());
            }).start();
        }
    }

}

/**
 * @Author: my_code
 * @Description: ;懒汉式(线程不安全)
 * 在多线程的环境先可能存在创建多个实例,所以在多条线程环境下不可使用这种情况
 * @Date: Create in 21:26 2020/9/12
 */

class Singleton {
    private static Singleton instance;

    private Singleton() {
    }

    //提供一个静态的公有方法,当使用时,才会去创建instance
    //即懒汉式
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

TYPE04 – 懒汉式( 线程安全)

public class SingletonTest04 {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Singleton instance = Singleton.getInstance();
                System.out.println(Thread.currentThread().getName() + "   instance.hashCode:" + instance.hashCode());
            }).start();
        }
    }
}

/**
 * @Author: my_code
 * @Description: ;懒汉式(线程安全,同步方法)
 * 效率太低,每个线程在想获得类的实例时,执行getInstance()方法都要进行同步。
 * 而其实每个方法只执行一次实例化代码就够了,后面的想获得该实例,直接return就行了。
 * 方法进行同步效率太低。
 * 实际开发中不推荐使用
 * @Date: Create in 21:26 2020/9/12
 */

class Singleton {
    private static Singleton instance;

    private Singleton() {
    }

    //提供一个静态的公有方法,当使用时,才会去创建instance,加入同步代码
    //即懒汉式
    public synchronized static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

TYPE05 – 双重检查

public class SingletonTest05 {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Singleton instance = Singleton.getInstance();
                System.out.println(Thread.currentThread().getName() + "   instance.hashCode:" + instance.hashCode());
            }).start();
        }
    }
}

/**
 * @Author: my_code
 * @Description: 双重检查
 * Double-Check概念是多线程开发中常使用到的,如代码中所示,我们进行了两
 * 次if (singleton == null)检查,这样就可以保证线程安全了。
 * 这样,实例化代码只用执行一次,后面再次访问时,判断if (singleton = null),
 * 直接return实例化对象,也避免的反复进行方法同步。
 * 线程安全:延迟加载,效率较高
 * 结论:在实际开发中,推荐使用这种单例设计模式
 * @Date: Create in 22:03 2020/9/12
 */

class Singleton {

    private static volatile Singleton instance;

    private Singleton() {
    }

    //提供一个静态的公有方法,加入双重检查代码,解决线程安全问题,同时解决懒加载问题
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

TYPE06 – 静态内部类

public class SingletonTest06 {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Singleton instance = Singleton.getInstance();
                System.out.println(Thread.currentThread().getName() + "   instance.hashCode:" + instance.hashCode());
            }).start();
        }
    }
}

/**
 * @Author: my_code
 * @Description: 静态内部类方式(推荐)
 * 特点:1.在外部类加载时,内部类不会被装载,利用静态内部类特点实现延迟加载,效率高
 *      2.类的静态属性只会在第一次加载类的是初始化,在类的参数时,其他线程无法进入,说以在创建单例时,线程是安全的。
 * @Date: Create in 22:18 2020/9/12
 */

class Singleton {

    //构造器私有化
    private Singleton() {
    }
    private static class SingletonInstance{
        private static final Singleton INSTANCE = new Singleton();
    }

    //提供一个静态公有的方法,直接返回SingletonInstance.INSTANCE
    public static Singleton getInstance(){
        return SingletonInstance.INSTANCE;
    }

}

TYPE07 – 枚举

public class SingletonTest7 {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Singleton instance = Singleton.SINGLETON;
                System.out.println(Thread.currentThread().getName() + "   instance.hashCode:" + instance.hashCode());
            }).start();
        }
    }
}

/**
 * @Author: my_code
 * @Description: 通过枚举实现(提倡使用  )
 * 特点:不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象
 * @Date: Create in 0:36 2020/9/13
 */
enum Singleton {
    SINGLETON;

    public void show() {
        System.out.println("我是通过枚创建单例");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
设计模式除了单例模式,还有很多其他常见的设计模式,例如: 1. 工厂模式(Factory Pattern):用于创建对象的模式,根据不同的条件返回不同的对象实例。 2. 观察者模式(Observer Pattern):定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。 3. 建造者模式(Builder Pattern):将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。 4. 适配器模式(Adapter Pattern):将一个类的接口转换成客户希望的另一个接口,使得原本不兼容的类可以一起工作。 5. 策略模式(Strategy Pattern):定义了一系列的算法,并将每个算法封装起来,使它们可以互相替换,使得算法可以独立于使用它的客户而变化。 6. 装饰器模式(Decorator Pattern):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰器模式比生成子类更为灵活。 7. 模板方法模式(Template Method Pattern):定义一个操作中的算法的骨架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。 8. 迭代器模式(Iterator Pattern):提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。 9. 外观模式(Facade Pattern):为子系统中的一组接口提供一个一致的界面,定义了一个高层接口,使得这个子系统更加容易使用。 10. 访问者模式(Visitor Pattern):表示一个作用于某对象结构中的各元素的操作,它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值