zoukankan      html  css  js  c++  java
  • Java设计模式--单例模式

    一、单例模式概述

    (一)定义:确保一个类只有一个实例,而且自行实例化并向整个系统提供这个实例场景,也就是说:确保某个类有且只有一个对象的场景,避免产生多个对象消耗过多的资源,或者某种类型的对象应该有且只有一个。

    (二)单例模式的特点

    1. 单例模式只能有一个实例。

    2. 单例类必须创建自己的唯一实例。

    3. 单例类必须向其他对象提供这一实例。

    (三)常见的两种方式:

    1. 饿汉式:类一加载的时候就创建对象
    2. 懒汉式:需要的时候才创建对象

    二、案例

    需求:创建一个Student类对象

    饿汉式

    public class Student {
    	private Student() {
    	}
    	
    	private static final Student stu = new Student();
    	
    	public static Student getStudent() {
    		return stu;
    	}
    }
    

    懒汉式

    public class Student {
    	private Student() {
    	}
    	
    	private static Student stu = null;
    	
    	public static Student getStudent() {
    		if(stu == null) {
    			stu = new Student();
    		}
    		return stu;
    	}
    }
    

    线程安全的懒汉式

    public class Student {
    	private Student() {
    	}
    	
    	private static Student stu = null;
    
    	public synchronized static Student getStudent() {
    		if(stu == null) {
    			stu = new Student();
    		}
    		return stu;
    	}
    }
    

    在main方法中获取Student实例对象

    public class StudentDemo {
    	public static void main(String[] args) {
    		Student stu = Student.getStudent();
    	}
    }
    
    

    三、JDK中单例模式的体现

    JDK中的RunTime类就是使用了饿汉式单例模式。其部分源码如下所示:

    public class Runtime {
        private Runtime() {}
        
        private static final Runtime currentRuntime = new Runtime();
        
        public static Runtime getRuntime() {
            return currentRuntime;
        }
    }
    

    其实这也告诉我们开发的时候尽可能的使用饿汉式的单例模式。

    四、单例模式的优缺点:

    优点
    在系统内存中只存在一个对象,因此可以节约系统资源,对于一些需要频繁创建和销毁的对象单例模式无疑可以提高系统的性能。
    缺点
    没有抽象层,因此扩展很难。
    职责过重,在一定程序上违背了单一职责

    Java新手,若有错误,欢迎指正!

  • 相关阅读:
    Django REST framework
    django写入csv并发送邮件
    GC收集器ParNew&CMS
    编写高质量的JavaScript代码
    Vue3.0 declare it using the "emits" option警告
    vue 3.0 router 跳转动画
    vue3.0 element-plus 表格合并行
    element-plus 时间日期选择器 el-date-picker value-format 无效等
    vue3.0中使用,一个元素中是否包含某一个元素。
    vue axios ajax 获取后端流文件下载
  • 原文地址:https://www.cnblogs.com/Java-biao/p/12577869.html
Copyright © 2011-2022 走看看