高效java

一、创建、销毁对象

1、考虑用静态工厂方法替代构造器

2、遇到多个构造器参数时要考虑用构建器

静态工厂和构造器有一个共同的局限性,它们不能很好的扩展到大量的可选参数,程序员一向习惯采用重叠构造器,在这种模式下,提供第一个只有必要参数的构造器,第二个构造器有一个可选参数,最后一个构造器包含所有的可选参数。

public People(String name,String sex){
  this(name,sex,0,0,0,"");
}
public People(String name,String sex,int age){
  this(name,sex,age,0,0,"");
}
public People(String name,String sex,int age,float height,float wigth){
  this(name,sex,age,height,wigth,"");
}
public People(String name,String sex,int age,float height,float wigth,String skin){
  this.name=name;
  this.sex=sex;
  this.age=age;
  this.height=height;
  this.wigth=wigth;
  this.skin=skin;
}

重叠的构造器方法可行,但是当有许多参数的时候,代码很难编写,并且难以阅读。

Builder方法:

public class People {
    private final String name;
    private final String sex;
    private final String address;
    private final float height;
    private final float weight;

    public People(Builder builder) {
        name = builder.name;
        sex = builder.sex;
        address = builder.address;
        height = builder.height;
        weight = builder.weight;
    }
}

public class Builder {
    public String name;
    public String sex;
    public String address;
    public float height;
    public float weight;

    public Builder(String name, String sex) {
        this.name = name;
        this.sex = sex;
    }

    public Builder setAddress(String address) {
        this.address = address;
        return this;
    }

    public Builder setHeight(float height) {
        this. height = height;
        return this;
    }

    public Builder setWeight(float weight) {
        this.weight = weight;
        return this;
    }

    public People build() {
        return new People(this);
    }
}


public class MainClass {
    public static void main(String[] args){
        People people = new Builder("pxc","女").setAddress("福州").setHeight(163).setWeight(45).build();
       
    }
}

运行结果:通过builder方法把参数写入对象中。

151451_sXv4_2874009.png

Builder模式易于阅读,参数灵活。

第四章 类和接口

1、使类和成员的可访问性最小化:尽可能使每个类或者成员不被外界访问。

实例域不能是共有的:包含共有可变域的类并不是线程安全的。

2、使可变性最小化

    2.1 不提供任何机会会修改对象状态的方法

    2.2 保证类不会被扩展

转载于:https://my.oschina.net/u/2874009/blog/791343

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值