zoukankan      html  css  js  c++  java
  • java# 认识设计模式# 单例模式及应用场景

    ## 单例模式介绍

    单例模式应用于一个类只有一个实例的情况,并且为其实例提供一个全局的访问点。对于某些创建比较频繁的类,可降低系统开销,省去频繁实例化对于像,减轻GC压力。

    ## 饿汉模式 

    在类加载时候就构建,急切初始化。(如果get方法未被使用,照成资源浪费)

    ```

    public class Student1 {

      // 2:成员变量初始化本身对象

      private static Student1 student = new Student1();
      // 1:构造私有

      private Student1() {}

      // 3:对外提供公共方法获取对象

      public static Student1 getSingletonInstance() {

        return student;

      }

    }

    ```

    ## 懒汉模式

    ```

    public class Student5 {
      private Student5() { }

      /* * 此处使用一个内部类来维护单例 JVM在类加载的时候,是互斥的,所以可以由此保证线程安全问题 */

      private static class SingletonFactory {

        private static Student5 student = new Student5();

      }

      /* 获取实例 */

      public static Student5 getSingletonInstance() {

        return SingletonFactory.student;

      }

    }

    ```

  • 相关阅读:
    Bottle python
    mongodb python pymongo
    Directory常用
    File类常用
    Path类的常用方法
    winfrom的单例模式
    325工厂模式和面向对象知识点总结(有点乱凑合看)
    音乐播放器自动播放下一首歌记录
    c#分页类(转)
    c# 简历生成器
  • 原文地址:https://www.cnblogs.com/xy-c/p/14313071.html
Copyright © 2011-2022 走看看