单例模式
[TOC]
定义和作用
目的:使类的一个对象成为该类系统中的唯一实例
定义:一个类有且仅有一个实例 并且自行实例化向整个系统提供

代码实现

package com.imooc.singleton;
//饿汉式:创建对象实例的时候直接初始化 空间换时间
public class SingletonOne {
//1、创建类中私有构造
private SingletonOne(){
}
//2、创建该类型的私有静态实例
private static SingletonOne instance=new SingletonOne();
//3、创建公有静态方法返回静态实例对象
public static SingletonOne getInstance(){
return instance;
}
}
package com.imooc.singleton;
//懒汉式:类内实例对象创建时并不直接初始化,直到第一次调用get方法时,才完成初始化操作
//时间换空间
public class SingletonTwo {
//1、创建私有构造方法
private SingletonTwo(){
}
//2、创建静态的该类实例对象
private static SingletonTwo instance=null;
//3、创建开放的静态方法提供实例对象
public static SingletonTwo getInstance(){
if(instance==null)
instance=new SingletonTwo();
return instance;
}
}
优缺点


场景

网友评论