java新手笔记12 单例

1.单例

package com.yfs.javase;

public class Singleton {
	
	//private static final Singleton single = new Singleton();//定义自己的对象引用
	private static  Singleton single;
	// 控制构造方法
	private Singleton() {

	}

	// 提供获取对象的方法
	public static Singleton getInstance() {
		if(single == null) {
			System.out.println("创建Singleton对象....");
			single = new Singleton();
		}
		return single;
	}

	public void sayHello() {
		System.out.println("Hello....");
	}

}

 2.单例测试

package com.yfs.javase;

public class SingleTest {

	
	public static void main(String[] args) {
//		Singleton s1 = new Singleton();
//		s1.sayHello();
//		
//		Singleton s2 = new Singleton();
//		s2.sayHello();
//		
//		final int a = 10;
		
		//a = 20;
		
//		System.out.println("s1 == s2 : " + (s1 == s2));
		Singleton s1 = Singleton.getInstance();
		
		Singleton s2 = Singleton.getInstance();
		
		s1.sayHello();
		s2.sayHello();
		
		System.out.println("s1 == s2 : " + (s1 == s2));
		
	}

}

 3.开关灯示例

package com.yfs.javase;

public class Light {
	// 属性编号 状态
	private int index;
	private boolean lighting = true;

	// 构造方法
	public Light(int index) {
		this.index = index;
		setIndex(index);
	}

	// 查看状态方法
	public boolean isLighting() {
		return lighting;
	}

	// 获取灯的编号
	public int getIndex() {
		return index;
	}

	// 根据编号设置灯的状态
	private void setIndex(int index) {

		for (int i = 1; i < index; i++) {
			if (index % i == 0) {
//				if (lighting) {//== true
//					lighting = false;
//				} else {
//					lighting = true;
//				}
//				lighting = lighting ? false : true;
				
				
				lighting = !lighting;
			}
		}
	}
}

 4.灯测试

package com.yfs.javase;

public class LightTest {

	public static void main(String[] args) {
		//灯数组
		Light[] lights = new Light[100];
		
		//创建对象
		for (int i = 0; i < lights.length; i++) {
			lights[i] = new Light(i + 1);
		}
		
		//查看灯的状态
		for (int i = 0; i < lights.length; i++) {
			//灯类必须查看状态方法
			if(lights[i].isLighting()){
				System.out.println("第 " + lights[i].getIndex() + " 灯是亮的");
			}
				
		}

	}

}

 5.乘法表

package com.yfs.javase;

public class Demo {
	
	private Demo() {
		
	}
	
	public static Demo get() {
		return new Demo();
	}

	public static void main(String[] args) {
		for (int i = 1,j = 1; i < 10; ) {
			System.out.print(j  + " * " + i + " = " + (i * j) + "   ");
			j++;//让列增长
			if(j == i + 1) {
				j = 1;
				System.out.println();
				i++;//行增长
			}
			
			
		}
	}
}
原文地址:https://www.cnblogs.com/feilongblog/p/4675340.html