Java中单例设计模式

来源:互联网 发布:焊接机器人编程 编辑:程序博客网 时间:2024/05/28 15:14

/*单例设计模式:即指在一个程序中只允许运行一个本类实例单例设计模式分为懒汉式和恶汉式*///懒汉式import java.util.*;class LazySingle {private static LazySingle ls = null;private String text = null;private LazySingle(){GregorianCalendar gc = new GregorianCalendar();text=gc.get(Calendar.YEAR)+"年"+gc.get(Calendar.MONTH)+"月"+gc.get(Calendar.DAY_OF_MONTH)+"日"+gc.get(Calendar.HOUR)+"时"+gc.get(Calendar.MINUTE)+"分"+gc.get(Calendar.SECOND)+"秒";//通过此时间信息,来判断对象创建时间。}//将该实例的构造函数私有化,不允许通过new关键字来创建本类对象。public static LazySingle getInstance()//对外提供静态方法,使得本类能够被实例化{if(ls==null)ls=new LazySingle();//通过自己创建自己的本类对象来获得实例return ls;}public String getText(){return this.text;}}//恶汉式class BadSingle{private static final BadSingle bs = new BadSingle();//注意,这里有final//final修饰变量的特点:对于一个final变量,如果是基本数据类型的变量,则其数值一旦在初始化之后便不能更改;如果是引用类型的变量,则在对其初始化之后便不能再让其指向另一个对象。//在这里单例设计模式修饰的是对象(也就是引用类型的变量),那么一旦被初始化,以后取得的都是本类对象private String text = null;private BadSingle(){GregorianCalendar gc = new GregorianCalendar();text=gc.get(Calendar.YEAR)+"年"+gc.get(Calendar.MONTH)+"月"+gc.get(Calendar.DAY_OF_MONTH)+"日"+gc.get(Calendar.HOUR)+"时"+gc.get(Calendar.MINUTE)+"分"+gc.get(Calendar.SECOND)+"秒";}public static BadSingle getInstance(){return bs;}public String getText(){return this.text;}}public class Single{public static void main(String[] args) throws Exception{//LazySingle ls = LazySingle.getInstance();//LazySingle ls1 = LazySingle.getInstance();//System.out.println((ls==ls1)+":::"+ls.getText()+":::"+ls1.getText());//两个对象其实都引用的用一个地址//BadSingle bs = BadSingle.getInstance();//BadSingle bs1 = BadSingle.getInstance();//System.out.println((bs==bs1)+":::"+bs.getText()+":::"+bs1.getText());//两个对象其实都引用的用一个地址new Thread(new ThreadLazySingle()).start();Thread.sleep(2000);new Thread(new ThreadLazySingle()).start();Thread.sleep(2000);new Thread(new ThreadLazySingle()).start();Thread.sleep(2000);new Thread(new ThreadLazySingle()).start();Thread.sleep(2000);new Thread(new ThreadLazySingle()).start();Thread.sleep(2000);new Thread(new ThreadBadSingle()).start();Thread.sleep(2000);new Thread(new ThreadBadSingle()).start();Thread.sleep(2000);new Thread(new ThreadBadSingle()).start();Thread.sleep(2000);new Thread(new ThreadBadSingle()).start();Thread.sleep(2000);new Thread(new ThreadBadSingle()).start();}public static void threadTest(){}}class ThreadLazySingle implements Runnable{private String text = null;public void run()//覆盖run方法{LazySingle ls = LazySingle.getInstance();System.out.println(ls.getText());}}class ThreadBadSingle implements Runnable{private String text = null;public void run()//覆盖run方法{BadSingle bs = BadSingle.getInstance();System.out.println(bs.getText());}}


运行结果:

2015年6月20日10时15分6秒2015年6月20日10时15分6秒2015年6月20日10时15分6秒2015年6月20日10时15分6秒2015年6月20日10时15分6秒2015年6月20日10时15分16秒2015年6月20日10时15分16秒2015年6月20日10时15分16秒2015年6月20日10时15分16秒2015年6月20日10时15分16秒

通过上面的结果来看,对象都是一样的。

0 0
原创粉丝点击