在Producer/Consumer 的Idiom中使用Delegate

当你生成一个实现producer idiom类的时候,使用deletate来通知consumer。这种方法相对于用接口更加灵活。Delegate是多点传送的,所以不用加额外的代码你就何以支持多用户。相对于用接口这样做可使类之间的耦合性降低。下面的类处理键盘输入并把它传给所有的registered listeners:


public   class  KeyboardProcessor
{
    
private OnGetLine theFunc = null;

    
public OnGetLine OnGetLineCallback
    
{
        
get
        
{
            
return theFunc;
        }

        
set
        
{
            theFunc 
= value;
        }

    }


    
public void Run()
    
{
        
// Read input.
        
// If there is any listeners, publish:
        string s;
        
do
        
{
            s 
= Console.ReadLine();
            
if (s.Length == 0)
                
break;
            
if (theFunc != null)
            
{
                System.Delegate[] funcs 
= theFunc.GetInvocationList();
                
foreach (OnGetLine f in funcs)
                
{
                    
try
                    
{
                        f(s);
                    }

                    
catch (Exception e)
                    
{
                        Console.WriteLine(
"Caught Exception: {0}", e.Message);
                    }

                }

            }

        }
 while (true);
    }

}




任何数目的listeners都可注册到producer,它们所要做的只是提供一个特定的函数:deletate。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值