zoukankan      html  css  js  c++  java
  • 为什么需要 单例设计模式(Singleton)?

    像下面的一个单例

    Java代码
    1. public class Singleton {  
    2.     private static Singleton instance = null;  
    3.     private Singleton(){};  
    4.     public static synchronized Singleton getInstance(){  
    5.         if(instance == null)  
    6.              instance = new Singleton();  
    7.         return instance;  
    8.      }  
    9.     public void doSomething(){  
    10.         //do something  
    11.      }  
    12. }  
    public class Singleton { private static Singleton instance = null; private Singleton(){}; public static synchronized Singleton getInstance(){ if(instance == null) instance = new Singleton(); return instance; } public void doSomething(){ //do something } }


    它要实现的主要目标,就是在一个应用中只维护一个Singleton实例

    但一个类在一个应用中也是唯一的,为什么不能直接以类作为单例呢?

    Java代码
    1. public final class AnotherSingleton{  
    2.     private AnotherSingleton(){}  
    3.     public static void doSomething(){  
    4.         //do something  
    5.      }  
    6. }  
    public final class AnotherSingleton{ private AnotherSingleton(){} public static void doSomething(){ //do something } }

    把类的所有方法都改为静态方法,

    所有属性都改为静态属性(我们可以把

    静态属性看成类的内部状态),

    但是不允许实例化,

    对类的操作相当于对单例的操作

    而且类也可以维护内部状态(通过静态私有属性)

    这完全满足了单例的要求。

    不知道为什么需要单例模式。。。


    因为我想不出来在什么情况下 单例可以满足需求

    而 类 不能。

  • 相关阅读:
    [转]拓扑排序
    [转]C++ string学习
    二叉树的前序遍历
    My Solution to Lowest Common Ancestor of a Binary Tree Part I(TopDown Approach)
    求二叉树节点总数
    二叉树的中序遍历
    轻松搞定面试中的二叉树题目
    VS2005 CrystalReport开发Web应用
    ASP.NET 2.0移动开发入门之使用模拟器
    [原创]Ajax UpLoadFile 多个大文件上传控件,已更新。
  • 原文地址:https://www.cnblogs.com/danghuijian/p/4400563.html
Copyright © 2011-2022 走看看