• 【设计模式】—— 单例模式Singleton


    前言:【模式总览】——————————by xingoo

      模式意图

      保证类仅有一个实例,并且可以供应用程序全局使用。为了保证这一点,就需要这个类自己创建自己的对象,并且对外有公开的调用方法。

      模式结构

      Singleton 单例类,内部包含一个本身的对象。并且构造方法时私有的。

      使用场景

      当类只有一个实例,而且可以从一个固定的访问点访问它时。

      代码结构

      【饿汉模式】通过定义Static 变量,在类加载时,静态变量被初始化。

    复制代码
     1 package com.xingoo.eagerSingleton;
     2 class Singleton{
     3     private static final Singleton singleton = new Singleton();
     4     /**
     5      * 私有构造函数
     6      */
     7     private Singleton(){
     8         
     9     }
    10     /**
    11      * 获得实例
    12      * @return
    13      */
    14     public static Singleton getInstance(){
    15         return singleton;
    16     }
    17 }
    18 public class test {
    19     public static void main(String[] args){
    20         Singleton.getInstance();
    21     }
    22 }
    复制代码

      【懒汉模式】

    复制代码
     1 package com.xingoo.lazySingleton;
     2 class Singleton{
     3     private static Singleton singleton = null;
     4     
     5     private Singleton(){
     6         
     7     }
     8     /**
     9      * 同步方式,当需要实例的才去创建
    10      * @return
    11      */
    12     public static synchronized Singleton getInstatnce(){
    13         if(singleton == null){
    14             singleton = new Singleton();
    15         }
    16         return singleton;
    17     }
    18 }
    19 public class test {
    20     public static void main(String[] args){
    21         Singleton.getInstatnce();
    22     }
    23 }
  • 相关阅读:
    python练习册 每天一个小程序 第0006题
    python练习册 每天一个小程序 第0005题
    [happyctf]部分writeup
    python练习册 每天一个小程序 第0004题
    [实验吧](web)因缺思厅的绕过 源码审计绕过
    python练习册 每天一个小程序 第0002题
    poj2185 Milking Grid
    hdu1711 Number Sequence
    poj1961 Period
    lightOJ 1017 Brush (III) DP
  • 原文地址:https://www.cnblogs.com/felix-/p/4319775.html
Copyright © 2020-2023  润新知