2019独角兽企业重金招聘Python工程师标准>>>
静态内部类的两种使用方式
1、什么是静态内部类?
请移步这里
2、静态内部类在生成单例模式中的应用:
为什么要使用静态内部类生成单例对象? 1、在类加载器加载过程中只加载一次,加载的时候生成对象,这利用了天然的类加载器功能,所以生成的对象只有一个,因为只加载一次。 2、这样可以避免并发加同步 double-checked模式锁生成对象,效率更高。
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";}}
3、静态内部类在builder设计模式中的使用 为什么要在builder设计模式中使用? 1、因为静态内部类的一个主要职责就是专为外部类提供服务,我们在外部类的基础上创建静态内部类BuilderHelper可以专为这个对象使用。 2、builder最重要的是在构造过程中返回this。 3、在java中关于StringBuilder中的append就是对builder模式的很好应用。
builder in wikipedia JDK中的设计模式
上代码:
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;}
}
对以上两个模式进行测试如下:
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