資料抽象的優點
- 幫助使用者避免編寫底層程式碼。
- 避免程式碼重複,提高可重用性。
- 可以在不影響使用者的情況下獨立更改類的內部實現。
- 有助於提高應用程式或程式的安全性,因為只向用戶提供重要資訊。
示例
js
class ImplementAbstraction {
// method to set values of internal members
set(x, y) {
this.a = x;
this.b = y;
}
display() {
console.log(`a = ${this.a}`);
console.log(`b = ${this.b}`);
}
}
const obj = new ImplementAbstraction();
obj.set(10, 20);
obj.display();
// a = 10
// b = 20