问题描述
我正在写一个网络流量分析器。 (使用Pcap.Net和LibPcap。)
在我的设计中,我有一个名为Controller的顶级类,而Controller创建了PacketBuffer的实例(二级类),PacketAnalyzer ,DatabaseWriter。
如下所示。
所有类都需要从Controller获取信息以相互协调,所以在某些类中,我通过这个(作为控制器)到二级课程。这似乎没问题吗?
大多数班级都会完成工作,并从sharedResultQueue存储或获取结果,sharedResultQueue是Controller的私人成员。
我将这个成员传递给二级课程,以便他们可以访问它。
看起来好吗?
谢谢!
Hi,
I am writing an network traffic analyzer. (using Pcap.Net and LibPcap.)
In my design, I have a top-level class called "Controller", and Controller creates instance (2nd-level classes) of "PacketBuffer", "PacketAnalyzer", "DatabaseWriter".
Like below.
All the classes need to get information from the Controller to coordinate with each other, so in some classes, I pass "this" (as a Controller) to the 2nd-level classes. Does this seem all right?
Most of the classes do their jobs, and store or get results from "sharedResultQueue", which is a private member of the Controller.
And I pass this member to the 2nd-level classes so they can access it.
Does this seem all right?
Thanks!
Class Controller
{
private PacketBuffer _buffer = new ...;
private PacketAnalyzer _analyzer;
private DatabaseWriter _writer;
private Queue<...> _sharedResultQueue = new Queue<...>;
public Controller()
{
_analyzer = new PacketAnalyzer(this, _buffer, _sharedResultQueue);
_writer = new DatabaseWriter(this, _sharedResultQueue);
}
...
}
Class PacketBuffer
{
...
}
Class PacketAnalyzer
{
private Controller _controller;
private PacketBuffer _buffer;
private Queue<...> _sharedResultQueue;
public PacketAnalyzer(Controller controller, PacketBuffer buffer, Queue<...> sharedResultQueue)
{
_controller = controller;
_buffer = buffer;
_sharedResultQueue = shareResultQueue;
}
...
}
Class DatabaseWriter
{
private Controller _controller;
private Queue<...> _sharedResultQueue;
public DatabaseWriter(Controller controller, Queue<...> sharedResultQueue)
{
_controller = controller;
_sharedResultQueue = shareResultQueue;
}
...
}
推荐答案
using System.Collections.Concurrent;
public class DHCP_Queue
{
public event EventHandler DataReceived;
private ConcurrentQueue<DHCP_Packet> packetQueue;
public DHCP_Queue()
{
this.packetQueue = new ConcurrentQueue<DHCP_Packet>();
}
protected virtual void OnDataReceived(EventArgs e)
{
if(DataReceived!=null)
{
DataReceived(this, e);
}
}
public void Produce(DHCP_Packet newPacket)
{
this.packetQueue.Enqueue(newPacket);
OnDataReceived(EventArgs.Empty);
}
public List<DHCP_Packet> ConsumeAll()
{
List<DHCP_Packet> latestPackets = new List<DHCP_Packet>();
DHCP_Packet packet = new DHCP_Packet();
while(this.packetQueue.TryDequeue(out packet))
{
latestPackets.Add(packet);
}
return latestPackets;
}
}
这篇关于OO编程如何正确设计我的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!