静态内部类的两种使用方式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
上代码: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