Java学习记录-面向对象(单例设计模式)

131 阅读1分钟

实例

//饿汉式
public class Single {//类一加载对象就存在
	static Single s = new Single();// 通过new在本类中创建一个本类对象

	private Single() {// 构造函数私有化
	}

	public static Single getInstance() {// 定义一个公有方法,将创建对象返回
		return s;

	}

}

//懒汉式
public class Single2 {//类加载进来没有对象,只有调用getinstance方法时才会创建对象,
//也叫延时加载形式
	private static Single2 s = null;

	private Single2() {

	}

	public static Single2 getInstance() {
		if (s == null)
			s = new Single2();
		return s;

	}

}



public class Test {
	private int num;
	private static Test t = new Test();

	private Test() {

	}

	public static Test getInstance() {
		return t;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public int getNum() {
		return num;

	}

}

public class SingleDemo {
	public static void main(String[] args) {
		Single s2 = Single.getInstance();
		Test t1 = Test.getInstance();
		Test t2 = Test.getInstance();
		t1.setNum(10);
		t2.setNum(20);
		System.out.println(t1.getNum());
		System.out.println(t2.getNum());
	}

}