泡泡

              宠辱不惊-闲看庭前花开花落
                           去留无意-漫观天外云展云舒
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

17)Mediator

Posted on 2007-09-21 14:56  AlanPaoPao  阅读(215)  评论(0)    收藏  举报
    中介者模式的目的是: 把一个特定对象集合的职责集中,进行封装
    实例代码:
abstract class AbstractChatroom
{
  
public abstract void Register(Participant participant);
  
public abstract void Send(string from, string to, string message);
}

class Chatroom : AbstractChatroom
{
  
private Hashtable participants = new Hashtable();
  
public override void Register(Participant participant)
  
{
    
if (participants[participant.Name] == null)
    
{
      participants[participant.Name] 
= participant;
    }

    participant.Chatroom 
= this;
  }

  
public override void Send(string from, string to, string message)
  
{
    Participant pto 
= (Participant)participants[to];
    
if (pto != null)
    
{
      pto.Receive(from, message);
    }

  }

}

class Participant
{
  
private Chatroom chatroom;
  
private string name;
  
public Participant(string name)
  
{
    
this.name = name;
  }

  
public string Name
  
{
    
get return name; }
  }

  
public Chatroom Chatroom
  
{
    
set { chatroom = value; }
    
get return chatroom; }
  }

  
public void Send(string to, string message)
  
{
    chatroom.Send(name, to, message);
  }

  
public virtual void Receive(string from, string message)
  
{
    Console.WriteLine(
"{0} to {1}: '{2}'", from, Name, message);
  }

}

class Beatle : Participant
{
  
public Beatle(string name)
    : 
base(name)
  
{
  }

  
public override void Receive(string from, string message)
  
{
    Console.Write(
"To a Beatle: ");
    
base.Receive(from, message);
  }

}

class NonBeatle : Participant
{
  
public NonBeatle(string name)
    : 
base(name)
  
{
  }

  
public override void Receive(string from, string message)
  
{
    Console.Write(
"To a non-Beatle: ");
    
base.Receive(from, message);
  }

}

class MainApp
{
  
static void Main()
  
{
    Chatroom chatroom 
= new Chatroom();
    Participant George 
= new Beatle("George");
    Participant Paul 
= new Beatle("Paul");
    Participant Ringo 
= new Beatle("Ringo");
    Participant John 
= new Beatle("John");
    Participant Yoko 
= new NonBeatle("Yoko");
    chatroom.Register(George);
    chatroom.Register(Paul);
    chatroom.Register(Ringo);
    chatroom.Register(John);
    chatroom.Register(Yoko);
    Yoko.Send(
"John""Hi John!");
    Paul.Send(
"Ringo""All you need is love");
    Ringo.Send(
"George""My sweet Lord");
    Paul.Send(
"John""Can't buy me love");
    John.Send(
"Yoko""My sweet love");
    Console.Read();
  }

}