<分区>
我想编写一个打印文档的应用程序。
哪种设计会更好?变体 A:
class Document
{
public string Title { get; set; }
public string Author { get; set; }
public string Content { get; set; }
// ...
}
class DocumentPrinter
{
public void PrintDocument(Document document)
{
// ...
}
}
这将提供一个专门的 DocumentPrinter 类,它只进行打印。或者向 Document 类本身添加一个 Print() 方法会更好,就像这里(变体 B):
public class Document
{
public string Title { get; set; }
public string Author { get; set; }
public string Content { get; set; }
public void Print()
{
// ...
}
}
两种变体的隐含权衡是什么?哪一个在可维护性和架构方面更好?
我会说变体 A 更好,因为它会满足“ 单一职责原则”。但是变体 B 使用起来会更直观。