开发者

Performing a common action on derived types

开发者 https://www.devze.com 2022-12-18 17:18 出处:网络
Is there a neat way to make several classes (which say derive from 1 interface), to each perform a same action? Think of http modules in ASP.NET which serve each request (Each the key word) - is there

Is there a neat way to make several classes (which say derive from 1 interface), to each perform a same action? Think of http modules in ASP.NET which serve each request (Each the key word) - is there a way开发者_如何学编程 to perform some common action on derived types? Reflection may be one way, though I would be interested in a way at a base class level.

Thanks


Not with only an interface; you'd want an abstract class in the middle there:

abstract class Whatever : IFooable {
    public virtual void Do () {
        PreDo();
    }

    protected abstract void PreDo();
}

Then you call Do, and PreDo is automatically called first on all implementing types.

(Edit: Just to be clear, I made Do virtual so this means if you re-implement it you should call base.Do() as the first thing, just to ensure that it actually calls the parent method).


If your classes all derive from a common base class, you could put this logic in your common base class.


If I understand what you are asking correctly, then perhaps an event handler is the way to go?

If you need a bunch of objects to respond to some action, then events (also called "message passing") is the way to go.

Something like this?

class Foo
{
     public event EventHandler PerformAction;

     private void OnActionNeeded()
     {
          // A bunch of Bars need to do something important now.

          if (PerformAction != null)
                 PerformAction.Invoke();
     }

}

class Bar
{
   public Bar(Foo fooToWatch)
   {
         fooToWatch.PerformAction += new EventHandler(Foo_PerformAction);
   }

   void Foo_PerformAction(object sender, EventArgs e)
   {
        // Do that voodoo that you do here.
   }
}


May not be a complete answer but I am tempted to think in terms of AOP and attributes.

some references:

http://www.codeproject.com/KB/cs/ps-custom-attributes-1.aspx

http://www.postsharp.org/contributions/documentation/removing-duplicate-code-in-functions


The Template Method design pattern may apply to what you're asking.

http://www.dofactory.com/Patterns/PatternTemplate.aspx


The overall point of designing an interface is to provide a protocol between two components and hide the implementation part. The interfaces serve as a communication medium. And what you are asking seem to be specific to implementaion. Which can be cleanly handled using utility classes(singleton with the method) I do not suggest to have abstract class in ur current scenario.

0

精彩评论

暂无评论...
验证码 换一张
取 消