知識點
單例設計模式
1.不允許用戶創建這個類的一個對象 將類的構造方法私有化
2.在自己的類里提供創建對象的方法
數組里保存的都是對象的引用
改變數組里面對象的值
原始對象的值也改變
因為代價都指向同一個內存空間
Collection.shuffle(); 打亂數組順序
技術的使用
public class MyClass {
public static void main(String[] args){
//1.正常情況下創建一個對象
Poker.shared.test();
Player.getInstance().count += 1;
Player p =Player.getInstance();
p.count +=1;
Player p2 =Player.getInstance();
p2.count +=1;
System.out.println(p2.count);
}
}
class Poker{
//1.默認構造函數
private Poker(){};
//default,sharedInstans,manager
//2.定義一個靜態的成員變量 記錄最高單例對象
//餓漢式 管你用不用先創建
public static final Poker shared = new Poker();
public void test(){
}
}
class Player{
public int count;
//1.私有化
private Player(){};
//2.創建靜態變量
private static Player shared = null;
//3.提供給外部一個訪問的方法
//懶漢式 用的時候才創建
public static Player getInstance (){
Object b = new Object();
synchronized (b) {
if (shared == null) {
//如果沒有創建 那么就創建一個
shared = new Player();
}
}
return shared; }
}
class Test2{
public static void main(String[] args){
//泛型
ArrayList<Person> people = new ArrayList<>();
//獲取數組元素個數
people.size();
//添加數據
Person xw = new Person();
people.add(xw);
Person zs = new Person();
people.add(zs);
//訪問數據
Person xw2 = people.get(0);
xw2.name = "小王";
System.out.println(xw.name);
//LinkedList 雙鏈表
}
}
class Person{
public String name;
}
隨筆
今天好累,去打球放松一下