A simple singleton

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/boatImpish/article/details/88411210

Singleton

This should be the first to come into contact with design patterns, and very easy to understand. But also to be able to knock them out and fast, right! Singleton first section of the code to:

class Singleton {
	private static volatile Singleton instance = null; // 加上 volatile 保证即时性,多个线程看到的变量是一样的,就是最新的状态。
	private Singleton(){};
	
	public static Singleton getInstance () {
		if (instance == null){						// 4, 这是第四步,让锁只走一次
			synchronize(Singleton.class){ 			// 3, 这是第三步,保证只有同时只有一个线程能创建对象,但是还是有一个问题,锁也是一个很重的操作,不能每次获取对象的时候都经过锁这个操作吧,这样太消耗性能了。
				if (instance == null) {			 	// 2, 这是第二步,加一个判空防止对象重复创建,尽量减小内存消耗,到现在还没有考虑到多线程的影响
					instance = new Singleton();    	// 1, 这是第一步,首先得创建一个对象
				}
			}
		}
		return instance;
	}
}

Well, the singleton pattern written, Singleton pattern has a lot of writing, which considered singleton lazy, right, created only in singleton to use this time.
Time to think, understanding will gradually deepened. Low space-time universe, the Milky Way, the solar system, the Earth, the Earth's rotation from west to east, as seen from Earth the sun rises in the West down, which has something of the concept, then the concept of human nature have a left and right direction, facing east, left for the North right hand for the South. China has 24 solar terms divide the year, interestingly, 24 solar terms corresponding to 24 time zones 1-24 are 23 regions, there is a region 24-1. Then the cycle is more than. Talk about any high-tech stuff, this is a person to survive the most basic things. One more point, the Chinese poetry in the description of the scene that season is a must. Chunxiao, as well as Du Fu's Spring Night Rain, rain is written masterpiece. It should at the moment of the King. Write these things, constantly remind ourselves to continue to progress ha ha

Guess you like

Origin blog.csdn.net/boatImpish/article/details/88411210