Ngôn Ngữ Lập Trình C#
public class Document : IStorable
{
public void Read()
{
}
public void Write()
{
}
}
Bây giờ trách nhiệm của chúng ta, với vai trò là người xây dựng lớp Document phải
cung cấp một thực thi có ý nghĩa thực sự cho những phương thức của giao diện IStorable.
Chúng ta phải thực thi tất cả các phương thức của giao diện, nếu không trình biên dịch sẽ báo
một lỗi. Sau đây là đoạn chương trình minh họa việc xây dựng lớp Document thực thi giao
diện IStorable.
Ví dụ 8.1: Sử dụng một giao diện.
using System;
// khai báo giao diện
interface IStorable
{
// giao diện không khai báo bổ sung truy cập
// phương thức là public và không thực thi
void Read();
void Write(object obj);
int Status
{
get;
set;
}
set
{
status = value;
}
}
// lưu trữ giá trị thuộc tính
private int status = 0;
}
public class Tester
{
static void Main()
{
// truy cập phương thức trong đối tượng Document
Document doc = new Document(“Test Document”);
doc.Status = -1;
doc.Read();
Console.WriteLine(“Document Status: {0}”, doc.Status);
// gán cho một giao diện và sử dụng giao diện
IStorable isDoc = (IStorable) doc;
isDoc.Status = 0;
Thực Thi Giao Diện
179
.
.
Ngôn Ngữ Lập Trình C#
isDoc.Read();
Console.WriteLine(“IStorable Status: {0}”, isDoc.Status);
}
}
phân cách giữa hai giao diện:
public class Document : IStorable, ICompressible
Thực Thi Giao Diện
180
.
.
Ngôn Ngữ Lập Trình C#
Do đó Document cũng phải thực thi những phương thức được xác nhận trong giao diện
ICompressible:
public void Compress()
{
Console.WriteLine(“Implementing the Compress Method”);
}
public void Decompress()
{
Console.WriteLine(“Implementing the Decompress Method”);
}
Bổ sung thêm phần khai báo giao diện ICompressible và định nghĩa các phương thức của
giao diện bên trong lớp Document. Sau khi tạo thể hiện lớp Document và gọi các phương
thức từ giao diện ta có kết quả tương tự như sau:
Creating document with: Test Document
Implementing the Read Method for IStorable
Implementing Compress
Mở rộng giao diện
C# cung cấp chức năng cho chúng ta mở rộng một giao diện đã có bằng cách thêm các
phương thức và các thành viên hay bổ sung cách làm việc cho các thành viên. Ví dụ, chúng ta
có thể mở rộng giao diện ICompressible với một giao diện mới là ILoggedCompressible.
Giao diện mới này mở rộng giao diện cũ bằng cách thêm phương thức ghi log các dữ liệu đã
lưu:
interface ILoggedCompressible : ICompressible
void Write(object obj);
int Status { get; set;}
}
// giao diện mới
interface ICompressible
{
void Compress();
void Decompress();
}
// mở rộng giao diện
interface ILoggedCompressible : ICompressible
{
void LogSavedBytes();
}
// kết hợp giao diện
interface IStorableCompressible : IStorable, ILoggedCompressible
{
void LogOriginalSize();
}
interface IEncryptable
{
void Encrypt();
void Decrypt();
}
public class Document : IStorableCompressible, IEncryptable
{
Thực Thi Giao Diện
182
.
.