java建造者模式静态内部类,静态内部类的使用方式

静态内部类的两种使用方式

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模式的很好应用。

上代码:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值