java-静态变量,单例模式

static关键字. 静态变量  

static(不在堆里面也不在栈里面, 在数据区(data seg)):

--类名直接 . 出来的变量是静态变量, 每个类里面的静态变量只有一份, 是公用的(赋值后每个实例化的类都可使用)
--静态方法中不可访问非静态成员
--静态变量和静态方法不需要实例化

package com.hanqi.test;

public calss Dog{
       public static int num;    //静态属性      
       //这里还可以写其他变量
} 
public Dog(){
      num++;
}   
//这里是要get和set一下的.有了返回值,main中调用时就可以如下所示用 点 调用了
 1 //在main 中
 2 packae com. hanqi.test;
 3 public class Main{
 4    public static void main (String[] args){
 5      Dog d1 = new Dog()     System.out.println(Dog.num);      //输出结果为1    拿类名 . 出来的就是静态的
 7 
 8      Dog d2 = new Dog()     System.out.println(Dog.num);       //输出结果为2
10 }    
11 }

这个方法可以作为计数时用.

public void print(){

System.out.println("这是第"+num+"只狗");

}

main中:   

Dog d1 = new Dog();   d1.print();  
Dog d2 = new Dog();   d2.print();  



---end--------------

单例模式 ,
 1 public class Danli {
 2 //构造方法定义成私有的,对外不公开,
 3     //外面没法通过new一个方法来获得一个实例
 4     private static Danli helloworld;
 5     private int count;
 6     private Danli() {}  
 7     //对外提供了下面的方法,可以通过类名.下面的方法名
 8     //获取这个实例
 9     
10     
11     public static Danli Add() {
12         if(helloworld == null) {
13             helloworld = new Danli();
14         }
15         return helloworld;
16     }
17     
18     
19     public int getCount() {
20         return count;
21     }
22 
23     public void setCount(int count) {
24         this.count = count;
25     }
26 }

main中:

public static void main(String[] args) {
        Danli he = Danli.Add();
        Danli he2 = Danli.Add();
        he.setCount(5);
        System.out.println(he2.getCount());
        System.out.println(he2 == he);
                 //==对比的是位置;
        //单例模式无论实例化多少,都指向同一个对象;
    }    
11.20-1文件中  2...








原文地址:https://www.cnblogs.com/ziyanxiaozhu/p/7868594.html