473,769 Members | 4,280 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inter-object event messaging (Mediator Pattern?) (very long sorry)

Hi all,

Please bear with me as I've only started programming in C# 2 weeks ago
and this is my first contact with OOP.

I ran into a situation where I needed to catch an event in an object
that had no connection or reference to the object that triggered it.

It goes something like this: (not syntactically correct..it's just for
the idea)

main()
{ A a;
C c;
a.Run();
}

class A
{ B b;
C c;

Run()
{ // Trigger the Event here}
} // class

class B
{ C c;
}

class C
{ // Catch and handle the event here
}

Which means that the event would be handled by the 3 instances of C.

>From My research I gathered that I should be using something called
the "Mediator Pattern".
Unfortunately I could not find a working example of this.

Also, from what I was able to understand, to make it work with this
pattern would require that I derive class C from an abstract
"participan t". Is that right ?

I then kind of gave up on trying to make it work with this pattern
(out of frustration at my failures) and proceeded to try and implement
something that I was a bit more familiar with (from my backgroung with
PCS):
The Publish / Subscribe model (is that also known as a pattern?)
I was pleasantly surprised that it worked.
Here's my working implementation:

All classes use the following:
using System;
using System.Collecti ons.Generic;
using System.Text;

With the class Dispatcher also using:
using System.Collecti ons;
class Program
{
static void Main(string[] args)
{
A a = new A();
C c = new C("C1");

for(int i = 1; i <= 3; i++)
{
a.Run(i);
}
Console.ReadKey ();
}
}

class A
{
B b = new B();
C c = new C("C2");

public void Run(int i)
{
Dispatcher.Publ ish("MyEvent", "Hello #" + i.ToString());
}
}

class B
{
C c = new C("C3");
}

class C
{
private string name;

public C(string name)
{
this.name = name;
Dispatcher.Subs cribe("MyEvent" , OnMyEvent);
}

public void OnMyEvent(objec t appEventParams)
{
string textReceived = (string)appEven tParams;
Console.WriteLi ne(textReceived + " received in " + name);
}

}

public delegate void AppEventHandler (object appEventParams) ;

static class Dispatcher
{
private static Hashtable registry = new Hashtable();

public static void Subscribe(strin g appEvent, AppEventHandler
appEventHandler )
{
Subscription(ap pEvent, appEventHandler , true);
}

public static void Unsubscribe(str ing appEvent,
AppEventHandler appEventHandler )
{
Subscription(ap pEvent, appEventHandler , false);
}

private static void Subscription(st ring appEvent,
AppEventHandler appEventHandler , bool add)
{
ArrayList list;

if (add)
{
if (registry[appEvent] == null)
registry.Add(ap pEvent, new ArrayList());

list = (ArrayList)regi stry[appEvent];
list.Add(appEve ntHandler);
}
else
{
if (registry[appEvent] != null)
{
list = (ArrayList)regi stry[appEvent];
list.Remove(app EventHandler);
}
}
}

public static void Publish(string appEvent, object
appEventParams)
{
ArrayList list;
AppEventHandler appEventHandler ;

if (registry[appEvent] != null)
{
list = (ArrayList)regi stry[appEvent];

for (int i = 0; i < list.Count; i++)
{
appEventHandler = (AppEventHandle r)list[i];
if (appEventHandle r != null)
appEventHandler (appEventParams );
}
}
}
}
The ouput is:
Hello #1 received in C3
Hello #1 received in C2
Hello #1 received in C1
Hello #2 received in C3
Hello #2 received in C2
Hello #2 received in C1
Hello #3 received in C3
Hello #3 received in C2
Hello #3 received in C1

Here are my questions (about time you'll say...sorry about that too
long preambule):

1) Is 'this" somehow a valid implementation of the Mediator pattern
and if not, it is known under another name ? (I hope it's not one of
those anti-pattern)

2) If it's not a valid implementation of the Mediator pattern (or
another "good" pattern), is there any reason why you would advise
"against" this approach. Did I miss an obvious flaw ? Did I do a big
no-no ?

3) Could you "please" (pretty, pretty please) give me a valid
implementation of the Mediator pattern that would give me the exact
same behavior as in my example. (If possible please give me working
code)

4) Any other comments, good of bad, that you think might help me with
this problem.

Thanks a lot in advance.

Apr 24 '07 #1
1 1735
I don't have time to read through and think about your whole question but a
working mediator pattern implementation in C# is to be found here:
http://www.dofactory.com/Patterns/Pa...or.aspx#csharp - don't know
if it does exactly the same your code does.
Maybe it will clarify something you need to have clarified.

<ha*****@yahoo. comwrote in message
news:11******** **************@ s33g2000prh.goo glegroups.com.. .
Hi all,

Please bear with me as I've only started programming in C# 2 weeks ago
and this is my first contact with OOP.

I ran into a situation where I needed to catch an event in an object
that had no connection or reference to the object that triggered it.

It goes something like this: (not syntactically correct..it's just for
the idea)

main()
{ A a;
C c;
a.Run();
}

class A
{ B b;
C c;

Run()
{ // Trigger the Event here}
} // class

class B
{ C c;
}

class C
{ // Catch and handle the event here
}

Which means that the event would be handled by the 3 instances of C.

>>From My research I gathered that I should be using something called
the "Mediator Pattern".
Unfortunately I could not find a working example of this.

Also, from what I was able to understand, to make it work with this
pattern would require that I derive class C from an abstract
"participan t". Is that right ?

I then kind of gave up on trying to make it work with this pattern
(out of frustration at my failures) and proceeded to try and implement
something that I was a bit more familiar with (from my backgroung with
PCS):
The Publish / Subscribe model (is that also known as a pattern?)
I was pleasantly surprised that it worked.
Here's my working implementation:

All classes use the following:
using System;
using System.Collecti ons.Generic;
using System.Text;

With the class Dispatcher also using:
using System.Collecti ons;
class Program
{
static void Main(string[] args)
{
A a = new A();
C c = new C("C1");

for(int i = 1; i <= 3; i++)
{
a.Run(i);
}
Console.ReadKey ();
}
}

class A
{
B b = new B();
C c = new C("C2");

public void Run(int i)
{
Dispatcher.Publ ish("MyEvent", "Hello #" + i.ToString());
}
}

class B
{
C c = new C("C3");
}

class C
{
private string name;

public C(string name)
{
this.name = name;
Dispatcher.Subs cribe("MyEvent" , OnMyEvent);
}

public void OnMyEvent(objec t appEventParams)
{
string textReceived = (string)appEven tParams;
Console.WriteLi ne(textReceived + " received in " + name);
}

}

public delegate void AppEventHandler (object appEventParams) ;

static class Dispatcher
{
private static Hashtable registry = new Hashtable();

public static void Subscribe(strin g appEvent, AppEventHandler
appEventHandler )
{
Subscription(ap pEvent, appEventHandler , true);
}

public static void Unsubscribe(str ing appEvent,
AppEventHandler appEventHandler )
{
Subscription(ap pEvent, appEventHandler , false);
}

private static void Subscription(st ring appEvent,
AppEventHandler appEventHandler , bool add)
{
ArrayList list;

if (add)
{
if (registry[appEvent] == null)
registry.Add(ap pEvent, new ArrayList());

list = (ArrayList)regi stry[appEvent];
list.Add(appEve ntHandler);
}
else
{
if (registry[appEvent] != null)
{
list = (ArrayList)regi stry[appEvent];
list.Remove(app EventHandler);
}
}
}

public static void Publish(string appEvent, object
appEventParams)
{
ArrayList list;
AppEventHandler appEventHandler ;

if (registry[appEvent] != null)
{
list = (ArrayList)regi stry[appEvent];

for (int i = 0; i < list.Count; i++)
{
appEventHandler = (AppEventHandle r)list[i];
if (appEventHandle r != null)
appEventHandler (appEventParams );
}
}
}
}
The ouput is:
Hello #1 received in C3
Hello #1 received in C2
Hello #1 received in C1
Hello #2 received in C3
Hello #2 received in C2
Hello #2 received in C1
Hello #3 received in C3
Hello #3 received in C2
Hello #3 received in C1

Here are my questions (about time you'll say...sorry about that too
long preambule):

1) Is 'this" somehow a valid implementation of the Mediator pattern
and if not, it is known under another name ? (I hope it's not one of
those anti-pattern)

2) If it's not a valid implementation of the Mediator pattern (or
another "good" pattern), is there any reason why you would advise
"against" this approach. Did I miss an obvious flaw ? Did I do a big
no-no ?

3) Could you "please" (pretty, pretty please) give me a valid
implementation of the Mediator pattern that would give me the exact
same behavior as in my example. (If possible please give me working
code)

4) Any other comments, good of bad, that you think might help me with
this problem.

Thanks a lot in advance.

Apr 24 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3600
by: cppaddict | last post by:
I have a design question which I am posting here because the implementation will be in C++ and I think there may be C++ specific language constructs (eg, friends) that might be relevant to the solution. I am implementing the Mediator pattern to create an event-driven app. The Collaborators (which watch for various events and which all have a reference to the Mediator object) will call handleEvent(Event e) on the Mediator object when...
7
1423
by: Mrkrich | last post by:
I have one procedure that will take very long time before it finishs. During its running, I provide users a button to cancel this process if they don't want it to run anymore. I have one varible for process status if user click the cancel button this variable will change to False and the procedure will check this variable during it run The problem is I don't know how the program receive the button's event during this procedure running.
0
892
by: Philippe | last post by:
Hi, I've got troubles with event messaging between 2 classes. In a WinForm, a DataGrid has a ComboBox. I need to use the SelectedIndexChanged of the cbo to perform some DB updates. ComboBox is done by a component that exposes 2 classes: DataGridComboBox that inherits from ComboBox and DataGridComboBoxColumnStyle that inherits from DataGridColumnStyle. In DataGridComboBox I declared an event: Public Event ppSelectedIndexChanged() This...
0
990
by: Horst Klein | last post by:
Hi I'm searching a sample how to use a ChangeManager (Based on the Mediator Pattern) How can help me? Best regards Horst
1
2713
by: FluffyCat | last post by:
I finally pieced together what I think is a good example of the Mediator Pattern in PHP 5. See what you think. http://www.fluffycat.com/PHP-Design-Patterns/Mediator/ I have, per request, tried to simplify my test program structure a bit. testMediator.php has only one html tag in it - a <BR>. This is in my new writeln() function, which adds '<'.'BR'.'>' to each line and
3
3566
by: Rich Denis | last post by:
Hello, I am in need of assistance trying to figure out how to 'Unit Test' my Event Based Async Pattern (http://msdn2.microsoft.com/e7a34yad.aspx) web service calls. Specifically how to test the event handler. So as I see it, the auto generated web service proxy will create the custom event arg class that is passed to the event handler. That is all in good, the problem is that the custom event arg class is not publicly creatable. So...
3
5669
by: =?Utf-8?B?aGVyYmVydA==?= | last post by:
I need to build an event-based asynchronous pattern (around a send/receive messaging API). Is there a step-by-step guidance about how to write code for the EBAP ? Does any book cover this theme (VB.NET preferred)? thanks herbert
1
4163
by: halekio | last post by:
Hi all, Please bear with me as I've only started programming in C# 2 weeks ago and this is my first contact with OOP. I ran into a situation where I needed to catch an event in an object that had no connection or reference to the object that triggered it. It goes something like this: (not syntactically correct..it's just for the idea)
12
13515
by: Ahmad Jalil Qarshi | last post by:
Hi, I have an integer value which is very long like 9987967441778573855. Now I want to convert it into equivalent Hex value. The result must be 8A9C63784361021F I have used sprintf(pHex,"%0X",9987967441778573855). But it only returns 8
0
10036
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9987
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7404
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6662
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5294
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5444
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3952
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3558
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2812
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.