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

单态模式Singleton

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

第一个类  God.java

package com.jzm;
/*
 * 懒汉式单态模式
 *
 * author   jzm
 */
public class God {
     private static God god = null;
 
     private God(){
         
     }
   public synchronized static God getInstance()
     {
       if (god == null) {
    god = new God();
  }
      return god; 
     }
}

第二个类TestGod.java

package com.jzm;

public class TestGod {
 
 public static void main(String[] args) {
   
    God god1 = God.getInstance();
    God god2 = God.getInstance();
 
    System.out.println(god1);
    System.out.println(god2);
 }
}

 

上述两个类任选一个, 即可实现单态模式~!

抱歉!评论已关闭.