java的单例模式


单例模式: 保证类的实例只有一个。

  • 构造函数私有化,提供一个可以获取到对象的静态公开方法。

饿汉式单例模式(Eager Initialization)

public class Singleton {
    // 自己创建一个对象
    private static Singleton s = new Singleton(); // 提供一个私有构造函数

    private Singleton() {
    }
    // Instance : 实例化 
    // synchronized: 同步 (保证这个方法被线程使用完之后, 其他线程才可以使用到。)

    public static synchronized Singleton getInstance() {
        return s;
    }

}

class Test1 {
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance(); // 判断是否为同一个对象
        System.out.println(s1 == s2);
    }
}

懒汉式单例模式(Lazy Initialization)

public class SingletonA {
    // 定义一个静态变量
    private static SingletonA sa;

    // 私有化构造函数
    private SingletonA() {
    }

    // 提供一个静态函数
    public static synchronized SingletonA getInstance() {
        if (sa == null) {
            sa = new SingletonA();
        }
        return sa;
    }
}

用单例模式写一个冒泡排序算法

import java.util.Arrays;

public class SingletonSort {
    private static SingletonSort ss;

    private SingletonSort() {
    }

    public static synchronized SingletonSort getInstance() {
        if (ss == null) {
            ss = new SingletonSort();
        }
        return ss;
    }

    public int[] bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }


        return arr;
    }
}

class TestAA {
    public static void main(String[] args) {
        SingletonSort ss = SingletonSort.getInstance();
        int[] a = {1, 3, 43, 64, 21, 343, 11, 33};
        a = ss.bubbleSort(a);
        System.out.println(Arrays.toString(a));
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值