| |
Mediator Design Pattern
C# implementation:
using System;
using System.Collections;
namespace design_pattern_mediator
{
// "Mediator"
class Mediator
{
// Fields
private Hashtable m_plugins = new Hashtable();
static Mediator m_mediator = null;
// Methods
private Mediator() {}
public static Mediator GetMediator()
{
if (m_mediator == null)
m_mediator = new Mediator();
return m_mediator;
}
public void AddPlugin( Plugin plugin )
{
if( m_plugins[ plugin.Name ] == null )
m_plugins[ plugin.Name ] = plugin;
plugin.Mediator = m_mediator;
}
public void SendMessage( string from, string to, string message )
{
Plugin p = (Plugin)m_plugins[ to ];
if( p != null )
p.Receive( from, message );
}
}
// "Abstract Colleague"
interface IPlugin
{
void Send(string to, string msg);
void Receive(string from, string msg);
}
// "Concrete Colleague"
class Plugin
{
// Fields
private Mediator m_mediator;
private string name;
// Constructors
public Plugin( string name )
{
this.name = name;
}
// Properties
public string Name
{
get{ return name; }
}
public Mediator Mediator
{
set{ m_mediator = value; }
get{ return m_mediator; }
}
// Methods
public void Send( string to, string message )
{
Mediator.SendMessage( name, to, message );
}
virtual public void Receive(
string from, string message )
{
Console.WriteLine( "{0} to {1}: '{2}'",
from, this.name, message );
}
}
///
/// MediatorApp test
///
public class MediatorApp
{
public static void Main(string[] args)
{
// Create mediator
Mediator m = Mediator.GetMediator();
// Create plugins and register them
Plugin Plugin1 = new Plugin("Plugin 1");
Plugin Plugin2 = new Plugin("Plugin 2");
m.AddPlugin( Plugin1 );
m.AddPlugin( Plugin2 );
// Messages exchanging
Plugin1.Send( "Plugin 2", "Message from Plugin 1 to Plugin 2" );
Plugin2.Send( "Plugin 1", "Message from Plugin 2 to Plugin 1" );
Console.Read();
}
}
}
|
The results are below:
Plugin 1 to Plugin 2: 'Message from Plugin 1 to Plugin 2'
Plugin 2 to Plugin 1: 'Message from Plugin 2 to Plugin 1'
Link Partners:
- digital signatures for secure e-mail solutions, digital ssl certificates, two factor authorization software, computer security software. You can also find totally customizable solutions for ISP SSL systems, two factor authentication for secure network access, smart cards and secure tokens.
- wireless internet service
Let us help you in selecting wireless internet connections.
- start a home business
Latest news and ideas about home based business is right here.
- start a home business
Making huge money is right in the home ,just click here..
|