什么是单例
保证一个类仅有一个实例, 并提供一个访问它的全局访问点.
主要解决: 一个全局使用的类频繁地创建与销毁.
何时使用: 当您想控制实例数目, 节省系统资源的时候.
关键代码: 构造函数是私有的.
优点:
1. 在单例模式中, 活动的单例只有一个实例, 对单例类的所有实例化得到的都是相同的一个实例. 这样就 防止其它对象对自己的实例化, 确保所有的对象都访问一个实例
2. 提供了对唯一实例的受控访问.
3. 由于在系统内存中只存在一个对象, 因此可以 节约系统资源, 当 需要频繁创建和销毁的对象时单例模式无疑可以提高系统的性能.
4. 避免对共享资源的多重占用.
缺点:
1. 不适用于变化的对象, 如果同一类型的对象总是要在不同的用例场景发生变化, 单例就会引起数据的错误, 不能保存彼此的状态.
2. 由于单利模式中没有抽象层, 因此单例类的扩展有很大的困难.
3. 单例类的职责过重, 在一定程度上违背了 "单一职责原则".
- public class Singleton {
- private final static Singleton INSTANCE = new Singleton();
- private Singleton(){}
- public static Singleton getInstance(){
- return INSTANCE;
- }
- }
- public class Singleton {
- private static Singleton singleton;
- private Singleton() {}
- public static synchronized Singleton getInstance() {
- if (singleton == null) {
- singleton = new Singleton();
- }
- return singleton;
- }
- }
- public class Singleton {
- private Singleton() {}
- private static class SingletonInstance {
- private static final Singleton INSTANCE = new Singleton();
- }
- public static Singleton getInstance() {
- return SingletonInstance.INSTANCE;
- }
- }
- public class User {
- public static User getInstance() {
- return SingletonDemo04.INSTANCE.getInstance();
- }
- private static enum SingletonDemo04 {
- INSTANCE;
- // 枚举元素为单例
- private User user;
- private SingletonDemo04() {
- System.out.println("SingletonDemo04");
- user = new User();
- }
- public User getInstance() {
- return user;
- }
- }
- public static void main(String[] args) {
- User u1 = User.getInstance();
- User u2 = User.getInstance();
- System.out.println(u1 == u2);
- }
- }
- public class Singleton {
- private static volatile Singleton singleton;
- private Singleton() {}
- public static Singleton getInstance() {
- if (singleton == null) {
- synchronized (Singleton.class) {
- if (singleton == null) {
- singleton = new Singleton();
- }
- }
- }
- return singleton;
- }
- }
来源: http://www.bubuko.com/infodetail-2991203.html