views:

76

answers:

2

Let's say I have three object A, B, C.
B is the implementation of following interface:

interface D
{
    event EventHandler<OrderEventArgs> OrderCreated;
    event EventHandler<OrderEventArgs> OrderShipped;
}

I would add two functions in B which will raise the events in the interface.

class B
{
  RaiseOrderCreated();
  RaiseOrderShipped();
}

A is the hosting class and will call B's functions to raised the specified events. I hope in C I can listen to the interface B or class C, whenever the events in B are raised, C can get notified, then C can have reactive to the events.

I am thinking about how to implement this mechanism in C# and Java.
Any help or hints will be great appreciated !

+1  A: 

So you'd have an EventListener called C, some object called A which has a field of type B that is some kid of implementation of D.

Typically in Java you design D differently:

interface D {
   static final String ORDER_PROPERTY="ORDER";
   void setOrder(Order order);
   Order getOrder();
}

class B implements D {
   // delegate object to implement support for event listeners and event firing
   private java.beans.PropertyChangeSupport propertyChangeSupport = new java.beans.PropertyChangeSupport(this);
   private Order order = null; // field that holds current order
   @Override
   public void setOrder(Order order) {
      Order old = this.order;
      this.order = order;
      propertyChangeSupport.firePropertyChange(ORDER_PROPERTY, old, order);
   }
   // more B code here
}
Thanks, do you have any solution in C# ? Is there similar mechanism in C#? If I don't use the beans.PropertyChangeSupport, any other java solution ?
MemoryLeak
Well in Java you could code the event listener notification logic manually (which is all the PropertyChangeSupport object does), but why would you?
This got lost in the previous comment: I guess there'll be a C# equivalent to the java.beans object (I'm not much of a C# coder), if not it is a trivial thing to implement... you need a methods to add() and remove() listeners and to fire() and event.
A: 

Implement this pattern: http://en.wikipedia.org/wiki/Observer_pattern

Droo