单例模式

来源:互联网 发布:服装批发软件手机版 编辑:程序博客网 时间:2024/06/05 15:30

  单例模式:计算机是可以同时执行多个命令的,比如一台咖啡机,当机内咖啡容量为空时,就补充咖啡,但是如果存在两个实例时,在咖啡机为空时,两个实例都判断出为空,就加入了两份咖啡,这样就会造成溢出,造成损失,所以要设置只存在一个实例。代码:

  

/**
* 咖啡机
* */
public class Coffee {
//增加咖啡机的咖啡
private static final int ADD = 1; 
//咖啡机的咖啡还有或者已满,不注入
private static final int STOP = 0; 
// 注入咖啡
private static int infunde;
private static Coffee coffee;

private Coffee(int infunde) {
super();
this.infunde = infunde;
}

/**
*
*address:Coffee实例,为空就创建实例,不为空就直接返回实例
*return: 返回实例
*/
public static Coffee getCoffeeInstance(){
if(coffee == null){
coffee = new Coffee(Coffee.STOP);
}
return coffee;
}

public int getInfunde() {
System.out.println("您的咖啡已经满了,请取走,慢慢享用,欢迎下次光临!");
return infunde;
}

public void setInfunde(int infunde) {
System.out.println("注入咖啡");
this.infunde = infunde;
}

public void infundeCoffee(int state){
if(state == Coffee.ADD){
setInfunde(500);
}else {
System.out.println("咖啡未用完,不需要增加");
}
}
}

测试类:

public static void main(String[] args) {
//单例模式测试
Coffee coffee = Coffee.getCoffeeInstance();
System.out.println(coffee);
Coffee coffee1 = Coffee.getCoffeeInstance();
System.out.println(coffee1);
//获取咖啡
coffee.getInfunde();
coffee.infundeCoffee(1);
}

结果:

com.Singleton.Coffee@659e0bfd
com.Singleton.Coffee@659e0bfd
您的咖啡已经满了,请取走,慢慢享用,欢迎下次光临!
注入咖啡

//上面两个地址相同,证明是同一实例

0 0
原创粉丝点击