Đóng gói

Khái niệm

Đóng gói là nguyên tắc kết hợp dữ liệu với các thao tác hợp lệ trên dữ liệu đó, đồng thời hạn chế truy cập trực tiếp vào phần trạng thái nội bộ. Mục tiêu là giữ cho đối tượng luôn ở trạng thái hợp lệ và giảm phụ thuộc ngoài ý muốn.

Ví dụ quản lý số dư

class BankAccount:
	def __init__(self):
		self._balance = 0

	def deposit(self, amount):
		self._balance += amount

	@property
	def balance(self):
		return self._balance


account = BankAccount()
account.deposit(100)
print(account.balance)
class BankAccount
{
	private decimal _balance;

	public void Deposit(decimal amount)
	{
		_balance += amount;
	}

	public decimal Balance => _balance;
}

BankAccount account = new BankAccount();
account.Deposit(100);
Console.WriteLine(account.Balance);
class BankAccount {
	#balance = 0;

	deposit(amount) {
		this.#balance += amount;
	}

	get balance() {
		return this.#balance;
	}
}

const account = new BankAccount();
account.deposit(100);
console.log(account.balance);
#include <iostream>
using namespace std;

class BankAccount {
    double balance = 0;
public:
    void deposit(double amount) {
        balance += amount;
    }

    double getBalance() const {
        return balance;
    }
};

int main() {
    BankAccount account;
    account.deposit(100);
    cout << account.getBalance() << endl;
    return 0;
}
class BankAccount {
    private _balance: number = 0;

    deposit(amount: number): void {
        this._balance += amount;
    }

    get balance(): number {
        return this._balance;
    }
}

const account = new BankAccount();
account.deposit(100);
console.log(account.balance);

Kết luận

Đóng gói không phải để giấu dữ liệu một cách hình thức, mà để bảo vệ quy tắc của đối tượng. Khi các lớp bắt đầu kế thừa lẫn nhau, cần hiểu tiếp về Kế thừa.

Ghi chú theo ngôn ngữ

Thông tin</div>

Python dùng quy ước đặt tên để chỉ mức truy cập: tên bắt đầu bằng _ (một gạch) là “protected” theo quy ước, __ (hai gạch) kích hoạt name mangling làm tên khó truy cập từ bên ngoài. Không có từ khóa private cứng.

C++ có ba từ khóa: public, protected, private. Mặc định các thành viên trong classprivate, trong structpublic. friend cho phép lớp/hàm khác truy cập thành viên private.

C# có 6 mức truy cập: public, private, protected, internal, protected internal, private protected. Mặc định thành viên là private. Property (get/set) là cách chuẩn để bao bọc trường private.

JavaScript từ ES2022 có trường private thật sự với cú pháp #fieldName. Trước đó, đóng gói thường dùng closure hoặc quy ước đặt tên _fieldName.

TypeScript có từ khóa private, protected, public kiểm tra tại compile time. Từ TypeScript 3.8 hỗ trợ cả # private field của JavaScript cho kiểm tra runtime.

v/programming/oop/inheritance/).

Bình luận