单例模式应用

Emperor类中的代码:

 1 package org.hanqi.pn0120;
 2 
 3 public class Emperor {
 4     private static Emperor emperor=null;
 5     private Emperor()
 6     {
 7         
 8     }
 9     public static Emperor getInstance()
10     {
11         if(emperor==null)
12         {
13             emperor=new Emperor();
14         }
15         return emperor;
16     }
17     public void getName()
18     {
19         System.out.println("我是皇帝:太上皇");
20     }
21 }
View Code

Test类的代码:

 1 package org.hanqi.pn0120;
 2 
 3 public class Testemperor {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         System.out.println("创建皇帝1对象:");
 8         Emperor emperor1=Emperor.getInstance();
 9         emperor1.getName();
10         System.out.println("创建皇帝2对象:");
11         Emperor emperor2=Emperor.getInstance();
12         emperor2.getName();
13         System.out.println("创建皇帝3对象:");
14         Emperor emperor3=Emperor.getInstance();
15         emperor3.getName();
16         
17 
18     }
19 
20 }
View Code

posted on 2016-03-06 15:03  beens  阅读(132)  评论(0编辑  收藏  举报

导航