[英]Queuing different types of class instances
我想將2種類型的類實例排入隊列。 例如如下
要排隊的課程)
class A{
int a1;
int a2;
}
class B{
string b1;
string b2;
}
樣本1)
ConcurrentQueue<Object> queue = ConcurrentQueue<Object>();
queue.Enqueue(new A());
queue.Enqueue(new B());
Object item;
while (queue.TryDequeue(out item))
{
A a = item as A;
B b = item as B;
if(a != null){
}
else if(b != null){
}
}
樣本2)
class AorB{
public A a = null;
public B b = null;
public AorB(A a){ this.a = a; }
public AorB(B b){ this.b = b; }
}
ConcurrentQueue<AorB> queue = new ConcurrentQueue<AorB>();
queue.Enqueue(new AorB(new A()));
queue.Enqueue(new AorB(new B()));
AorB item;
while (queue.TryDequeue(out item))
{
if(item.a != null){
}
else if(item.b != null){
}
}
Sample1,Sample2或其他哪種更好的方法?
它們實際上都不是一個好的實現。 如果(如您在評論中提到的)它們是用於諸如Printing或Beeping之類的命令,並且它們的成員不同,那么您應該考慮它們在做什么 。 更好的解決方法是將他們正在做的事情提取到諸如
public interface ICommand
{
void Execute();
}
然后讓A和B實現ICommand,以便它們的打印和提示音由A和B處理。這樣,您的調用代碼將變為:
ConcurrentQueue<ICommand> queue = ConcurrentQueue<ICommand>();
queue.Enqueue(new A());
queue.Enqueue(new B());
Object item;
while (queue.TryDequeue(out item))
{
item.execute();
}
這也適用於“告訴,不要問”。
這是應用命令模式的理想情況。
讓每個對象實現一個公開接口的通用接口,該接口公開Execute
方法。 然后讓對象負責通過任何必要的方式執行命令。 通過將命令的執行封裝到對象本身中,這可以使代碼更簡潔,更可擴展。
這是記事本代碼,因此語法上可能會有一些小錯誤。
namespace
{
public interface ICommand
{
public void Execute();
}
public class CommandA : ICommand
{
public int value;
public void Execute()
{
// Do something here
}
}
public class CommandB : ICommand
{
public string value;
public void Execute()
{
// Do something here
}
}
public class Program
{
private Queue<ICommand> commands = new Queue<ICommand>();
public Program()
{
this.commands.Enqueue(new CommandA());
this.commands.Enqueue(new CommandB());
// Much later
while (item = this.commands.Dequeue())
{
item.Execute();
}
}
}
}
好吧,他們倆都沒有。 如果您需要排隊另一個類的實例,比如說C
,那么您的if
語句將變得可維護。
您必須考慮如何處理出隊物品。 如果只是將其存儲在隊列中,則對每種類型使用兩個或多個隊列。 如果您將它們用於任何類型的東西,則可以考慮使用將實現這些類型的接口或繼承其他類型的基類。
由於您尚未為此提供用例,因此我的建議是抽象的。
我實際上不會說1或2。
如果A和B共享一個公共接口,為什么不使用任何繼承,否則就只使用兩個隊列,如果它們沒有共同的接口,則針對每種對象使用一個隊列。
而且,如果它們沒有共同之處,也許您不應該只有一個代碼就可以同時使用它們。 根據使用情況,兩個線程(每種類型一個)可能看起來不錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.