首页 > 其他 > 详细

单例模式

时间:2016-01-14 14:10:42      阅读:222      评论:0      收藏:0      [点我收藏+]

单例设计模式:(Singlelon)

 

如果没有构造方法,会在编译时候自动构造一个什么都不干的构造方法

如果构造方法私有化,则外部不能使用 new 关键字实例化对象。

 

class Singleton{

    static Singleton instance = new Singleton() ;

    public void print(){

        System.out.println("Hello") ;

    }

}

public class Test{

    public static void main(String arg[]){

        Singleton s = null;

        s = Singleton.instance ;

        s.print() ;

    }

}

 

但是这样不符合类的封装性

所以需要用 private修饰instance

 

class Singleton{

    private static Singleton instance = new Singleton() ;

    public void print(){

        System.out.println("Hello") ;

    }

    public static Singleton getInstance(){

        return instance ;

    }

}

public class Test{

    public static void main(String arg[]){

        Singleton s = null;

        s = Singleton.getInstance() ;

        s.print() ;

    }

}

 

但是现在无论

S1 = Singleton.getInstance();

S2 = Singleton.getInstance();

S3 = Singleton.getInstance();

得到的都是同一个实例。

如果要控制一个类的实例化个数,那么就要锁定构造方法!!!

但是如果现在将getInstance方法中变为

Return new Singleton();也是有点小缺陷的

所以程序要这么写:
class Singleton{

    private static final Singleton INSTANCE = new Singleton() ;

    public void print(){

        System.out.println("Hello") ;

    }

    public static Singleton getInstance(){

        return INSTANCE ;

    }

}

public class Test{

    public static void main(String arg[]){

        Singleton s = null;

        s = Singleton.getInstance() ;

        s.print() ;

    }

}

 

 

可是对于单例设计模式有两种模式:

  1. 饿汉式
  2. 懒汉式

 

之前写的就是饿汉式,在Singleton定义的时候就准备好了一个对象,并没有关系这个对象有没有使用,懒汉式的特点是第一次使用 的时候实例化,以后都不实例化。

懒汉式:

class Singleton{

    private static final Singleton instance ;

    public void print(){

        System.out.println("Hello") ;

    }

    public static Singleton getInstance(){

        if(instance == null)

            return new Singleton() ;

        else

            return instance ;

    }

}

public class Test{

    public static void main(String arg[]){

        Singleton s = null;

        s = Singleton.getInstance() ;

        s.print() ;

    }

}

单例模式

原文:http://www.cnblogs.com/da-peng/p/5129777.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!