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

    总体来说设计模式分为三大类:

    创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。

    结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。

    行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

    单例模式确保一个类只有一个实例,并且自行实例化向系统提供这个实例,单例模式分为懒汉式和饿汉式:

    饿汉式是线程安全的,但是相对节省运行时间:

    1 class Singleton1{
    2     private static Singleton1 instance = new Singleton1();
    3     
    4     private Singleton1(){}
    5     
    6     public static Singleton1 getInstance(){
    7         return instance;
    8     }
    9 }

    懒汉式如果不加锁不是线程安全的,但是相对浪费运行时间:

     1 class Singleton2{
     2     private static Singleton2 instance = null;
     3     
     4     private Singleton2(){}
     5     
     6     public static Singleton2 getInstance(){//在方法中加synchronized关键字才是线程安全的
     7         if(null == instance)
     8             instance = new Singleton2();
     9         return instance;
    10     }
    11 }

    另外,饿汉式还有一种使用内部类实现的方式:

     1 class Singleton3{
     2     static class Inner{
     3         static Singleton3 instance = new Singleton3();
     4     }
     5     
     6     private Singleton3(){}
     7     
     8     public static Singleton3 getInstance(){
     9         return Inner.instance;
    10     }
    11 }

    在开发中,饿汉式使用的比较多。

  • 相关阅读:
    IDEA 修改JavaWeb的访问路径
    坦克大战--Java类型 ---- (1)音乐播放
    codeforces 620C
    算法笔记之KMP算法
    算法笔记数组
    26. Remove Duplicates from Sorted Array
    哈夫曼树的证明
    Complete Binary Search Tree
    Root of AVL Tree
    .net framework环境
  • 原文地址:https://www.cnblogs.com/gsbm/p/4769957.html
Copyright © 2011-2022 走看看