zoukankan      html  css  js  c++  java
  • 单例模式

    -----------------------饿汉模式
    package com.imooc;
     
    /**
     * 单例模式Singleton
     * 应用场合:有些对象只需要一个就足够了:如古代皇帝、老婆
     * 作用:保证整个应用程序中某个实例有且只有一个,提高系统的安全性,运行的性能
     * 缺点:当前对象权利过重 
     * 类型:饿汉模式、懒汉模式
     * @author Administrator
     *
     */ 
    public class Singleton {
    /**
     * 饿汉模式的诠释:使用static以及在类的加载的时期就创建类的实例,所有形象比喻成没吃饱的汉子,戏称饿汉模式;
     * 懒汉模式的诠释:使用static以及在类的加载的时期没有创建类的实例,而是在获取的时候才去调用创建类的实例,比较懒;
     */
    //1.将构造方法私有化,不允许外界外界直接创建对象
    private Singleton(){
     
    }
     
    //2.创建类的唯一实例,使用private static 修饰
    private static Singleton instance=new Singleton();
     
     
    //3.提供一个获取实例的方法,使用public static 修饰
    public static Singleton getInstance(){
    return instance;
    }
     
    }

    -----------懒汉模式 


    package com.imooc;
     
    /**
     * 单例模式:懒汉模式
     * 区别: 饿汉模式:加载类是比较慢,但运行时获取对象的速度比较快,线程安全的
     *        懒汉模式:加载类是比较快,但是在运行时获取对象的速度比较慢,线程不安全的
     * @author Administrator
     *
     */
    public class Singleton2 {
     
    //1.将构造方法是有化,不允许外部直接创建类的实例
    private Singleton2(){
     
    }
     
    //2.创建类的唯一实例,使用privtate static 修饰
    private static Singleton2 instance;
     
    //3.提供一个用户获取实例的方法,使用public static修饰
    public static Singleton2 getInstance(){
    if(instance==null){
    instance=new Singleton2();
    }
    return instance;
    }
     
    }




    package com.imooc;
     
    /**
     *测试单例模式
     * @author Administrator
     *
     */
    public class Test {
     
     
    public static void main(String[] args) {
     
    //饿汉模式
    Singleton  s1=Singleton.getInstance();
    Singleton  s2=Singleton.getInstance();
    if(s1==s2){
    System.out.println("S1和S2是同一个实例");
    }else{
    System.out.println("S1和S2不是是同一个实例");
    }
     
    //懒汉模式
    Singleton  s3=Singleton.getInstance();
    Singleton  s4=Singleton.getInstance();
     
    if(s3==s4){
    System.out.println("S3和S4是同一个实例");
    }else{
    System.out.println("S3和S4不是是同一个实例");
    }
    }
    }
  • 相关阅读:
    window 7/8/10 安装nginx
    全面了解 Nginx 到底能做什么
    MySQL优化
    office 2013 破解工具 及 软件下载
    centos6+如何对外开放80,3306端口号或者其他端口号
    CentOS 中查看软件的版本号
    CentOS 中安装 mysql 5.7+
    STL入门大全(待编辑)
    Feign
    微信公众号
  • 原文地址:https://www.cnblogs.com/besthetiao/p/4591216.html
Copyright © 2011-2022 走看看