package com.gx.singleton;
/**
* 饿汉模式
* @author Administrator
*
*/
public class StoreHouse {
/**
* StoreHouse getInstance = new StoreHouse();
* 1.jvm栈放一些类的信息,
* 2.new StoreHouse(),放到堆里面
*
*3.jvm栈refrence(指针)指向堆
*
*
*
*/
private int quantity = 100;//仓库的容量
private static StoreHouse getInstance = new StoreHouse();
private StoreHouse(){
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
public static StoreHouse getInstance(){
return getInstance;
}
}
package com.gx.singleton;
/**
* 懒汉模式
* @author Administrator
*
*/
public class StoreHouse1 {
private int quantity = 100;//仓库的容量
private volatile static StoreHouse1 getInstance = null;
private StoreHouse1(){
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
public static StoreHouse1 getInstance(){
if(getInstance == null){
synchronized (StoreHouse1.class) {
if(getInstance == null ){
getInstance = new StoreHouse1();
}
}
}
return getInstance;
}
//getInstance = new StoreHouse1() 1.StoreHouse1 getInstance = null 2. getInstance- 3. new StoreHouse1()
}