tailieunhanh - Abstract Classes

Tóm tắt các lớp học Giao diện IToken có thể được thực hiện bởi nhiều lớp học khác nhau, một cho từng loại mã thông báo trong một tập tin mã nguồn # C: IdentifierToken, KeywordToken, LiteralToken, OperatorToken | Abstract Classes The IToken interface could be implemented by many different classes one for each type of token in a C source file IdentifierToken KeywordToken LiteralToken OperatorToken and PunctuatorToken. You might also have classes for comments and white space. In situations such as this it s quite common for parts of the derived classes to share common implementations. For example the duplication in the following two classes is obvious class IdentifierToken IToken public IdentifierToken string name name public virtual string Name return name . private string name class StringLiteralToken IToken public StringLiteralToken string name name public virtual string Name return name . private string name Duplication in code is a warning sign. You should refactor the code to avoid the duplication and reduce any maintenance costs. However there is a right way and a wrong way to do this. The wrong way is to push all the commonality up into the interface. This is wrong because you d then have to change the interface to a class because an interface can t contain any implementation . The right way to avoid the duplication is to refactor the common implementation into a new class created specifically for this purpose. For example class DefaultTokenImpl public DefaultTokenImpl string name name public string Name return name private string name class IdentifierToken DefaultTokenImpl IToken public IdentifierToken string name base name . class StringLiteralToken DefaultTokenImpl IToken public StringLiteralToken string name base name . This is a good solution but there is one thing that is still not quite right You can create instances of the DefaultTokenImpl class. This doesn t really make sense. The DefaultTokenImpl class exists to provide a common default implementation. Its sole purpose is to be inherited from. The DefaultTokenlmpl class is an abstractration of common functionality rather than an entity in its own right. NOTE If you find the .