初学者问题 - 封装和“代理类”

发布于 2024-11-30 07:18:20 字数 396 浏览 1 评论 0原文

在学习 C# 时,我从阅读其他人的代码中发现,通过使用某种“代理类”将某些类与程序分离是一种很好的做法。即那些具有私有数据的程序。

例如,假设我有一个数据库类,它执行几乎所有的数据库交互。它具有“发送数据”和“读取数据”方法。

我还有一个 Manager 类,在其中放置了 Database 类的私有实例。在这个管理器类中,我还包含了“从数据库读取数据”和“将数据发送到数据库”方法。所有这些所做的就是接受所需的参数并使用它们来运行数据库的读/写方法。

除了一些可以轻松从其他地方运行代码的杂项方法之外,Manager 的唯一目的是充当程序和数据库类之间的信使,以防止数据库需要直接在表单中实例化。

我是否走在正确的轨道上,或者我只是通过不简单地在表单中创建数据库对象并直接从那里运行所有内容来为自己创造更多工作?

While learning c#, I have picked up the implication from reading other people's code that it's good practice to separate certain classes from the program by use of a sort of "Proxy Class". Namely those programs with private data.

For instance, say I have database class that performs just about all of my database interactions. It has both a "Send data" and "Read Data" method.

What I also have is a Manager class, in which I have placed a private instance of the Database class. In this Manager class, I have also included a "Read Data from Database" and "Send Data to Database" method. All these do is accept the required parameters and use them to run the Database's Read/Write methods.

Other than a few misc methods whose code could easily be run from elsewhere, Manager's only purpose's to act as a messenger between the program and the Database class to prevent Database from needing to be instantiated directly in the form.

Am I on the right track here or am I just creating more work for myself by not simply creating a Database object in the form and running everything directly from there?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哆啦不做梦 2024-12-07 07:18:20

我同意约翰·桑德斯的观点——你在某种“正确性”领域使用这个类,但不是为了真正的目的。

正如您的示例中所述,代理类用作抽象。您的执行代码不需要了解有关数据源的任何信息 - 它只需提交数据请求并获取数据作为响应。代理向您隐藏了这个实现细节——它可以从平面文件、数据库、Web 服务中检索数据;这真的没关系。这使您的代码更加灵活,因为它不依赖于特定的数据库实现,并且还使其可测试,因为您可以在其中注入一些提供测试(“模拟”)数据的其他类。

I'm with John Saunders on this - you're using the class in some realm of "correctness", but not for a real purpose.

As described in your example, a proxy class is used as an abstraction. Your executing code doesn't need to know anything about the data source - it just submits a request for data and gets data back as a response. The proxy hides this implementation detail from you - it could retrieve the data from a flat file, a database, a web service; it really doesn't matter. This makes your code more flexible because it's not tied to a specific database implementation, and it also makes it testable because you can inject some other class in there that provides test ("mock") data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文