在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。
 

你可能感兴趣的:(String,null,Class)