单例模式

package Singleton;

public class Singleton {
	private static Singleton sin = new Singleton();
	private String str = "Qwq";
	
	private Singleton() {
		
	}
	
	public static Singleton getInstance() {
		return sin;
	}

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}
}
package Singleton;

public class testSingleton {

	public static void main(String[] args) {
		//Singleton s1 = new Singleton(); wrong, not visible
		
		Singleton s2 = Singleton.getInstance();
		System.out.println(s2.getStr());
		
		Singleton s3 = Singleton.getInstance();
		s3.setStr("Qaq");
		
		System.out.println(s2.getStr()+s3.getStr());
		System.out.println(s2==s3);  //指向同一个对象sin
		
	}
}

result:
单例模式_第1张图片

你可能感兴趣的:(java学习,java)