
利用 Getter 和 Setter 方法优化对象属性访问
面向对象编程中,Getter 和 Setter 方法是控制对象属性访问和修改的关键。它们能够有效保护对象内部数据,同时提供受控的访问方式。
以下以 Thermostat 类为例,该类包含一个名为 farenheit 的成员变量,用于存储华氏温度。我们将使用 Getter 和 Setter 方法改进其访问控制。
原始代码示例:
class thermostat { constructor(farenheit) { this.farenheit = 5 / 9 * (farenheit - 32); } get temperature() { return this.farenheit; } set temperature(farenheit) { this.farenheit = farenheit; }}
改进后的代码:
class thermostat { constructor(farenheit) { this.celsius = 5 / 9 * (farenheit - 32); } get temperature() { return this.celsius; } set temperature(celsius) { this.celsius = celsius; }}
改进说明:
将成员变量名称改为 celsius,更准确地反映其存储的是摄氏温度。在 Setter 方法中添加 celsius 参数,允许外部代码修改该变量。
使用方法:
const thermos = new Thermostat(76); // 设置华氏温度let temp = thermos.temperature; // 获取摄氏温度 (约 24.44)thermos.temperature = 26; // 设置摄氏温度temp = thermos.temperature; // 获取更新后的摄氏温度 (26)
通过 Getter 和 Setter 方法,我们增强了对 celsius 变量的访问控制,同时保留了外部代码修改其值的灵活性。 这种方法提高了代码的可维护性和安全性。
以上就是如何使用Getter和Setter方法更好地控制Thermostat类的温度访问?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1501903.html
微信扫一扫
支付宝扫一扫