作者:湛蓝天空jk | 来源:互联网 | 2023-10-13 08:37
java单利设计模式
思想:设计一个只创建一次的,类似配置信息的类
实现代码:
类一:
public class Test {
public static void main(String[] args) {
Single s1 = Single.getInstance();
Single s2 = Single.getInstance();
s1.setNum(12);
s2.setNum(24);
System.out.println(s1.getNum());
System.out.println(s2.getNum());
}
}
类二:
class Single{
private int num;
private static Single s =null;
private Single(){};
public static Single getInstance(){
if(s==null)
s=new Single();
return s;
}
public void setNum(int num){
this.num=num;
}
public int getNum(){
return num;
}
}
输出结果:
24
24