Singleton(单例模式)

public class Singleton {//饿汉模式
    public String name;
    private static Singleton instance=new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return instance;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Singleton ts1 = Singleton.getInstance();  
            ts1.setName("jason");  
            Singleton ts2 = Singleton.getInstance();  
            ts2.setName("0539");  
              
            ts1.printInfo();  
            ts2.printInfo();  
              
            if(ts1 == ts2){  
                System.out.println("创建的是同一个实例");  
            }else{  
                System.out.println("创建的不是同一个实例");  
            } 
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    public void printInfo() {  
        System.out.println("the name is " + name);  
    } 

}
/* public class Singleton{
     public String name;
     private volatile static Singleton instance;
     private Singleton(){}
     public static Singleton getInstance(){
         if(instance==null){
             synchronized(Singleton.class){
                 if(instance==null)
                 instance=new Singleton();
             }
             
            
         }
         return instance; 
     }
     
     public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        
        public void printInfo() {  
            System.out.println("the name is " + name);  
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Singleton ts1 = Singleton.getInstance();  
                ts1.setName("jason");  
                Singleton ts2 = Singleton.getInstance();  
                ts2.setName("0539");  
                  
                ts1.printInfo();  
                ts2.printInfo();  
                  
                if(ts1 == ts2){  
                    System.out.println("创建的是同一个实例");  
                }else{  
                    System.out.println("创建的不是同一个实例");  
                } 
        }
 }*/
 

 

posted @ 2015-06-17 11:14  ~每天进步一点点~  阅读(177)  评论(0编辑  收藏  举报