您的位置:首页 > 其它

课堂笔记-单例模式

2013-07-14 19:52 176 查看
单例模式:构造方法私有化,对外提供一个公共的静态的访问入口。

class Singleton1

{

//饿汉式

//只有一个私有的构造方法

private Singleton1(){

System.out.println("Hello,singleton 1...");

}

private static final Singleton1 instance1 = new Singleton1();

//对外提供一个公共的静态的方法

public static Singleton1 getInstance(){

return instance1;

}

}

class Singleton2

{

//懒汉式

//只有一个私有的构造方法

private Singleton2(){

System.out.println("Hello,singleton 2...");

}

private static Singleton2 instance2 = null;

//对外提供一个公共的静态的方法

public static Singleton2 getInstance(){

if( instance2==null ){

instance2 = new Singleton2();

}

return instance2;

}

}

public class SingletonTest

{

public static void main(String[] args){

Singleton1.getInstance();

Singleton2.getInstance();

}

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