单例模式 属于创建型模式 一个类只能有一个实例,并且自行实例化,必须自行向其他对象提供这个实例 关键代码实现: public class DataCenter { //static variable private static DataCenter singleton = null; //private constructor private DataCenter () { } //static method, synchronized public synchronized static DataCenter getInstance() { if (singleton == null) singleton = new DataCenter ();
return singleton; } 注意事项: 构造器不公开private getInstance方法的关键字synchronized static 使用场合: 任何只需要一个实例的地方 配置信息类(负责配置文件的解析) 管理者类 控制类 门面类 代理类
|
|