- package exercises;
- public class SingleTest
- {
- public int num;
- public void setNum(int num)
- {
- this.num=num;
- }
- public int getNum()
- {
- return num;
- }
- SingleTest(){}//你的你不算单例设计,构造器必须私有化.
- static SingleTest d=new SingleTest();
- public static SingleTest getInstance()
- {
- return d;
- }
-
- public static void main(String[] args)
- {
- SingleTest d1=SingleTest.getInstance();
- SingleTest d2=SingleTest.getInstance();
- d1.setNum(69);
- SingleTest d3=new SingleTest();//你在这里构建了一个新的对象.是new出来的.值肯定不一样.
- d3.setNum(5);
- System.out.println("d1="+d1.getNum()+" d2="+d2.getNum()+" d3="+d3.getNum());
- //d1=69 d2=69 d3=5答案是对的.
- }
- }
复制代码 |