靜態內部類的使用方式

靜態內部類的兩種使用方式html

一、什麼是靜態內部類?java

請移步這裏設計模式

二、靜態內部類在生成單例模式中的應用:併發

爲何要使用靜態內部類生成單例對象? 一、在類加載器加載過程當中只加載一次,加載的時候生成對象,這利用了自然的類加載器功能,因此生成的對象只有一個,由於只加載一次。 二、這樣能夠避免併發加同步 double-checked模式鎖生成對象,效率更高。oracle

package inner;

public class SingleObject {
   private  SingleObject(){}
   
   private static class  HelpHolder{
	   private  static   final  SingleObject   INSTANCE = new  SingleObject();
   }
   
   public static SingleObject   getInstance(){
	   return  HelpHolder.INSTANCE;
   }
   
   public String toString(){
	   return  "this is  a singleton object";
   }
   
}

三、靜態內部類在builder設計模式中的使用 爲何要在builder設計模式中使用? 一、由於靜態內部類的一個主要職責就是專爲外部類提供服務,咱們在外部類的基礎上建立靜態內部類BuilderHelper能夠專爲這個對象使用。 二、builder最重要的是在構造過程當中返回this。 三、在java中關於StringBuilder中的append就是對builder模式的很好應用。app

builder in wikipedia JDK中的設計模式測試

上代碼:ui

package inner;

public class Hero {
    private  String  name ;
    private  String  country;
    private  String  weapon;
    
    public String getName() {
		return name;
	}


	public String getCountry() {
		return country;
	}


	public String getWeapon() {
		return weapon;
	}

	public   static  class   HeroBuilder{
    	 private String name ;
    	 private String country;
    	 private String weapon;
    	public  HeroBuilder(String name){
    		this.name = name;
    	}
    	
    	public HeroBuilder  setCountry(String country){
    		    this.country = country;
    		    return this;
    	}
    	
    	public HeroBuilder setWeapon(String weapon){
    		this.weapon = weapon;
    		return this;
    	}
    	
        
        public Hero  build(){
        	return  new Hero(this);
        }
    }
    
    public Hero(HeroBuilder  hb){
    	this.name = hb.name;
    	this.country =hb.country;
    	this.weapon = hb.weapon;
    }
    
    public String  toString(){
    	return  this.name +"," +this.country +","+this.weapon;
    }
}

對以上兩個模式進行測試以下:this

package inner;

import inner.Hero.HeroBuilder;

public class Visitor {
	public static void main(String[] args) {
		Hero  hh =  new HeroBuilder("wqp").setCountry("china").setWeapon("gun").build();
		System.out.println(hh.toString());
		
		SingleObject   instance = SingleObject.getInstance();
		SingleObject   instance2 = SingleObject.getInstance();
		
		if(instance == instance2){
			System.out.println("they are  the same  object");
		}
		
		System.out.println(instance);
	}
	
	

}

測試輸出結果:設計

wqp,china,gun
they are  the same  object
this is  a singleton object
相關文章
相關標籤/搜索