TestForth

作者: 实在想不出昵称丶 | 来源:发表于2016-11-23 09:10 被阅读0次
109068745599023161.jpg
//做单例开发
/** 单例设计模式:解决一个类在内存中只存在一个对象

想要保证对象唯一。
1.为了避免其他程序过多建立给类对象,先禁止其他程序建立该类对象
2.在本类中自定义一个对象
3.可以对外提供访问方式

体现:
1.将构造函数私有化
2.在类中建立一个本类对象
3.提供一个方法可以获取该对象

*/

class Test {
//饿韩式
  private int num;
  public void setNum(int num){
    this.num=num;
  }
  public int getNum(){
    return num;
  }
  private static Test t=new Test();
  private Test(){
    //private static Test t=new Test();错误
  }
  public static Test getTest(){
    //方法调用,要么类名;要么对象;
    //此刻已经没有对象
    return t;
  }
}
/*懒汉式
class Test {
  private static Test t=null;
  private Test{

 }
 public static Test getTest(){
  if(t==null){
  t=new Test();
  }
  return t;
 }
}
*/
public class TestForth{
  public static void main(String[] args){
    Test t1=Test.getTest();
    Test t2=Test.getTest();//静态通过类名调用
    t1.setNum(23);
    System.out.println(t2.getNum());
    //**out: 23
    //无private
    /* Test t1=new Test();
    Test t2=new Test();
    t1.setNum(30);
    System.out.println("t2.getNum()");
    **out: 0
    */
  }
}


*** 清醒小刻 ***
**** 没错,我就是在瞎闹 ****

相关文章

  • TestForth

    *** 清醒小刻 ******* 没错,我就是在瞎闹 ****

网友评论

    本文标题:TestForth

    本文链接:https://www.haomeiwen.com/subject/zrpmpttx.html