静态类介绍
- java中 用static 修饰的类为静态类,静态类只能是内部类;
- 内部静态类,是外部类的成员,可以访问外部类成员(包括私有成员),但因为有static约束,和静态方法类似,只能访问静态成员/方法,不能访问普通成员/方法
//外部类
public class Outer {
//静态成员
private static int static_parm_out;
//普通成员
private int parm_out;
Outer(int static_val, int val) {
this.parm_out = val;
static_parm_out = static_val;
System.out.println(String.format("Outer class init"));
}
//内部静态类
static class InnerStatic {
private int parm_static_in;
InnerStatic() {
//内部静态类只能访问静态参数/方法
int static_value = Outer.static_parm_out;
//静态类内部无法访问普通成员parm_out
//int value = parm_out;
System.out.println(String.format("InnerStatic get Outer.static_parm_out value:{0}", static_value));
}
}
}
静态内部类使用
考虑一个类有非常一个类有非常多(十几个/几十个)的初始化参数,并且每次初始化使用的不同的参数组合时如何编码。
- 直接利用重载构造函数就会非常笨,需要反复确认构造器参数顺序,也更容易出错;
- 或者使用无参构造函数,然后将成员利用setter方法赋值,这样必须将类的成员定义为可变的(无法用final修饰)存在对象状态不一致风险,也容易出错;
- 利用内部静态类构建,示例如下:
代码说明:- 定位电脑工厂类ComputerFactory 为外部类,用来可以构建电脑,需要输入品牌,厂商等大量参数;
2.如果利用方法1需要复杂的构造函数;利用2,要为成员设置setter方法,造成“电脑被生产出来后,配置还可以改变”(我们希望生产出的对象是稳定的) - 如果利用静态内部类,通过建造者模式来进行实例化,如下
- 定位电脑工厂类ComputerFactory 为外部类,用来可以构建电脑,需要输入品牌,厂商等大量参数;
利用静态内部类,通过建造者模式实例化:
//构建一台苹果 macbook pro,红色1024GB存储
ComputerFactory macpro = new ComputerFactory.Builder("Apple", "macbook pro")
.withDisk(1024)
.withColor("red")
.build();
//构建一台黑色ThinkPad,x1,512GB存储,8192MB内存,4000HZ cpu
ComputerFactory thinkpad = new ComputerFactory.Builder("ThinkPad", "x1")
.withDisk(512)
.withColor("Black")
.withCPU(4000)
.withMemory(8192)
.build();
具体实现类
//电脑工厂类
public class ComputerFactory {
private final String brand;
private final String model;
private final String color;
private final int cpu_hz;
private final int memory_size;
private final int disk_size;
public ComputerFactory(Builder computerBuilder) {
this.brand = computerBuilder.brand;
this.model = computerBuilder.model;
this.color = computerBuilder.color;
this.cpu_hz = computerBuilder.cpu_hz;
this.memory_size = computerBuilder.memory_size;
this.disk_size = computerBuilder.disk_size;
}
/**
* 内部静态构造类
*/
static class Builder {
//构建一台电脑必填参数
private final String brand;
private final String model;
//可选参数可选,不指定按默认构建
private String color="Black";
private int cpu_hz = 1000;
private int memory_size = 1024;
private int disk_size = 521;
public Builder(String brand, String model) {
this.brand = brand;
this.model = model;
}
public Builder withColor(String c){
this.color=c;
return this;
}
public Builder withMemory(int memory){
this.memory_size=memory;
return this;
}
public Builder withCPU(int cpu){
this.cpu_hz=cpu;
return this;
}
public Builder withDisk(int disk){
this.disk_size=disk;
return this;
}
public ComputerFactory build(){
return new ComputerFactory(this);
}
}
}