将Java建造者模式转为Apex时遇变量访问问题求助
Apex建造者模式转换问题:子类无法访问父类成员变量的解决方案
问题概述
将Java建造者模式代码转换为Apex时,在ScrewBuilder类中调用chiller.setCoolingCapacity()等方法时提示变量不可见,即使将字段改为public也无法解决。
核心错误原因
- Apex默认访问修饰符为private:Java中未指定修饰符的成员是包级私有,但Apex中未指定修饰符的成员默认是
private。因此ChillerBuilder中的chiller变量和getChiller()方法默认是private,导致子类ScrewBuilder无法直接访问chiller,Director类也无法调用getChiller()。 - Math.round()参数类型不匹配:Apex的
Math.round()仅接受Decimal类型参数,直接传入double值会编译报错。 - 部分成员未明确访问修饰符:未指定修饰符的字段/方法会因Apex默认规则导致访问权限问题。
修正后的完整代码
1. RefrigerationType枚举
public enum RefrigerationType { R134, R12 }
2. Chiller实体类
public class Chiller { private Double coolingCapacity; private Double compressorPower; private Double EER; private RefrigerationType refrigerationType; public void setCoolingCapacity(Double coolingCapacity) { this.coolingCapacity = coolingCapacity; } public void setCompressorPower(Double compressorPower) { this.compressorPower = compressorPower; } public void setEER(Double EER) { this.EER = EER; } public void setRefrigerationType(RefrigerationType refrigerationType) { this.refrigerationType = refrigerationType; } public override String toString() { Integer roundedEER = Math.round(Double.valueOf(EER).toDecimal()); return 'Chiller [Cooling capacity = ' + coolingCapacity + ' compressor power input = ' + compressorPower + ' EER = ' + roundedEER + ' refrigeration type is ' + refrigerationType + ']'; } }
3. ChillerBuilder抽象类
public abstract class ChillerBuilder { protected Chiller chiller; public void createChiller() { chiller = new Chiller(); } public abstract void buildCapacity(); public abstract void buildCompressorPower(); public abstract void buildEER(); public abstract void buildRefrigerationType(); public Chiller getChiller() { return chiller; } }
4. ScrewBuilder具体建造者
public class ScrewBuilder extends ChillerBuilder { public override void buildCapacity() { Double capacity = ((12-7)*1042*1000/3600); chiller.setCoolingCapacity(capacity); } public override void buildCompressorPower() { Double power = ((12-7)*1042*1000/3600)*0.83; chiller.setCompressorPower(power); } public override void buildEER() { Double eer = ((12-7)*1042*1000/3600)/(((12-7)*1042*1000/3600)*0.83); chiller.setEER(eer); } public override void buildRefrigerationType() { chiller.setRefrigerationType(RefrigerationType.R134); } }
5. Director指挥者类
public class Director { private ChillerBuilder builder; public void setBuilder(ChillerBuilder b) { builder = b; } public Chiller buildChiller() { builder.createChiller(); builder.buildCapacity(); builder.buildCompressorPower(); builder.buildEER(); builder.buildRefrigerationType(); return builder.getChiller(); } }
关键修改说明
- 将
ChillerBuilder中的chiller变量改为protected,确保子类ScrewBuilder可以访问该成员。 - 将
ChillerBuilder的getChiller()方法改为public,让Director类能够调用获取构建好的Chiller实例。 - 修正
Chiller类toString()中的Math.round()调用,将Double转换为Decimal后再传入,匹配方法参数要求。 - 明确所有成员的访问修饰符,避免Apex默认private规则带来的访问权限问题。
- 调整方法命名为Apex标准驼峰命名法,提升代码可读性。
内容的提问来源于stack exchange,提问作者user20695159
相关产品推荐
相关产品推荐

