我有一个基本的面向对象架构问题。假设我在VB.NET中有一个名为OutputLog的类。它有方法“创建”,“写”和“读”。
在我的程序中,我有很多类,我想写一个日志文件。所以,如果我有一个适合我的启动课程,它有:
Public Class Main
logFile = new OutputLog()
logFile.create("c:\abc.log")
logFile.write("first entry to the log file")
End Class
Public Class Two
"I want to write to this same log file in this class"
End Class
Public Class OutputLog
Methods to "Create", "Write" and "Read"
End Class
建筑师的最佳方法是什么?我可以在Class 2的构造函数中传递对logFile的引用吗?这是处理这个问题的最佳方法吗?这意味着对于我想要写入日志文件的每个类,我需要在构造函数中传递logFile?
由于
答案 0 :(得分:0)
我可以通过两种方式来建立更好的架构:
a)使OutputLog的所有成员都是静态的,例如Create,Write和Read。 因此,您可以在任何地方调用这些成员。
b)阅读关于Singleton的一些内容。将OutputLog视为单例。这也可以解决问题。
这是我将logFile传递给每个构造函数的最后一件事。
答案 1 :(得分:0)
你的选择真的是:
更改OutputLog类以使用共享方法,然后您不需要该类的实例 - When to use Shared methods in .NET
将logFile更改为全局变量,每个类都可以使用它 - Declare global variables in Visual Studio 2010 and VB.NET
更改logFile以使用Singleton设计,以便只存在该类的一个副本 - singleton pattern in vb
您可以传递该类的副本,但这有点无意义,只是意味着您需要在添加更多类时添加越来越多的代码
答案 2 :(得分:0)
如果要在分离的类中写入相同的文件,则应将模块中的logfile var声明为public
假设您在项目中创建 Module1.vb ..添加此
Public logFile as New OutputLog
在您的班级
中Public Class Main
logFile.create("c:\abc.log")
logFile.write("first entry to the log file")
End Class
Public Class Two
logFile.write("this is from class two")
End Class