如果您有在代表非常不同事物的类中经常使用的功能,根据我的经验,它应该分为几类:
- 实用程序(例如字符串格式化、解析等)
- 横切关注点(日志记录、安全实施……)
对于实用程序类型的功能,您应该考虑创建单独的类,并在业务类中需要的地方引用实用程序类。
public class Validator
{
public bool IsValidName(string name);
}
class Patient
{
private Validator validator = new Validator();
public string FirstName
{
set
{
if (validator.IsValidName(value)) ... else ...
}
}
}
对于诸如日志记录或安全性等横切问题,我建议您研究面向方面的编程。
关于其他评论中讨论的 PrintA 与 PrintB 示例,这听起来像是工厂模式的绝佳案例。您定义一个接口,例如 IPrint、类 PrintA 和 PrintB,它们都实现了 IPrint,并根据特定页面的需要分配一个 IPrint 实例。
// Simplified example to explain:
public interface IPrint
{
public void Print(string);
}
public class PrintA : IPrint
{
public void Print(string input)
{ ... format as desired for A ... }
}
public class PrintB : IPrint
{
public void Print(string input)
{ ... format as desired for B ... }
}
class MyPage
{
IPrint printer;
public class MyPage(bool usePrintA)
{
if (usePrintA) printer = new PrintA(); else printer = new PrintB();
}
public PrintThePage()
{
printer.Print(thePageText);
}
}