单例模式: 保证类的实例只有一个。
- 构造函数私有化,提供一个可以获取到对象的静态公开方法。
饿汉式单例模式(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));
}
}