现在的位置: 首页 > 综合 > 正文

创建型模式-03单态模式

2013年09月09日 ⁄ 综合 ⁄ 共 1625字 ⁄ 字号 评论关闭
 

Singleton
 
问题引入:在我们平时编写程序的时候经常会new一些对象,而这些对象在使用意义上是一样的,那么我们每次new这种类型对象的时候,在内存就存在多个使用意义相同的对象存在了。很大程度上浪费的系统的资源。
 
Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
其具体实现分2种形式饱汉式和饿汉式
饿汉式:由使用前就由类装载器装载,代码实现如下(注意构造函数一定要overwrite成私有的,以便外部不能够new出该对象)
 
publicclass Hungry
{
    privatestatic Hungry hungry = new Hungry();
    privateintindex = 0;
    private Hungry(){}
    publicstatic Hungry getInstance()
    {
        returnhungry;
    }
    publicint getIndex()
    {
        index++;
        returnindex;
    }
}
这种实现方式,在我们平时开发多用于计数器,比如说计算访问量。
这种使用方式的缺点就是系统加载慢,不能捕获异常,对于系统并发量大的情况会出现线程安全问题。饱汉式能够很好的解决上面的问题
 
 
饱汉式:延迟初始化,在第一次使用的时候实例化对象。代码实现如下
publicclass Full
{
    privatestatic Full full = null;
    privateintindex = 0;
    private Full(){}
    publicstaticsynchronized Full getInstance()
    {
        if(full == null)
        {
            try{
            full = new Full();
            }catch(Exception e){}
        }
        returnfull;
    }
    publicint getIndex()
    {
        index++;
        returnindex;
    }
}
 
 
通过单态模式可以进一步演化,又出现了多态模式,其实现原理与单态模式相同,主要强调的是系统中,只存在几个这样的对象
代码如下
 
publicclass Multion
{
    privatestatic Multion mt1 = null;
    privatestatic Multion mt2 = null;
    privateintindex =0;
    private Multion(){}
    publicstaticsynchronized Multion getInstance1()
    {
        if(mt1==null)
        {
            try{
                mt1 = new Multion();
            }catch(Exception e){}
         }
        returnmt1;
      }
    publicstaticsynchronized Multion getInstance2()
    {
        if(mt2==null)
        {
            try{
                mt2 = new Multion();
            }catch(Exception e){}
         }
        returnmt2;
     }
    publicint getIndex()
    {
        index++;
        returnindex;
    }
 
}
 
注意:这种单态是针对于一个jvm来说,如果处于分布式系统那么是不适用的,也就是说如果是基于容器的应用最好不要使用,因为不清楚应用程序将来的部署环境
 
 

 

抱歉!评论已关闭.