您的位置:首页 > 编程语言 > Java开发

JAVA中单例模式讲解

2012-06-18 15:42 267 查看
等等 单例模式的俩种方式:

饿汉式

class Singleton {

private static Singleton instance=new Singleton();

private Singleton(){}

static Singleton getInstance() {

return instance;

}}

懒汉式c

class Singleton {

private static Singleton instance=null;

private Singleton(){}

static Singleton getInstance() {

if(instance==null)

instance=new Singleton();

return instance;

}}

应用比如:一个系统连接多台打印机,

public class A{

//声明了一个私有的a对象

private A a=null;

//将其舒适化构造方法为私有的,外部无法实例化

private A(){}

//声明一个方法为public类型让外部访问 比如 A a=A.newinstance(); 这样来得到一个A的对象

public A newinstance(){

//第一次为空就能得到对象并且返回出去,如果不为空则代码改对象已经被实例化过,则不与返回对象,

if(a==null){

return a;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: