中介设计模式

中介设计模式是一种重要且应用广泛的行为设计模式。Mediator通过在对象之间引入一个层来实现对象的解耦,从而使对象之间的交互通过该层发生。如果对象之间直接交互,则系统组件彼此紧密耦合,这使得维护成本更高,并且不难扩展。Mediator模式的重点是在对象之间提供一个用于通信的中介,并帮助实现对象之间的失去耦合。

null

空中交通管制员是调解人模式的一个很好的例子,在这种模式中,机场控制室充当不同航班之间通信的调解人。Mediator充当对象之间的路由器,它可以有自己的逻辑来提供通信方式。

UML图中介设计模式

图片[1]-中介设计模式-yiteyi-C++库

设计组件

  • 调解人: 它定义了同事对象之间通信的接口。
  • 调解人: 它实现了中介接口,并协调同事对象之间的通信。
  • 同事: 它定义了与其他同事沟通的接口
  • 同事: 它实现了同事接口,并通过其中介与其他同事进行通信

让我们看一个中介设计模式的例子。

class ATCMediator implements IATCMediator
{
private Flight flight;
private Runway runway;
public boolean land;
public void registerRunway(Runway runway)
{
this .runway = runway;
}
public void registerFlight(Flight flight)
{
this .flight = flight;
}
public boolean isLandingOk()
{
return land;
}
@Override
public void setLandingStatus( boolean status)
{
land = status;
}
}
interface Command
{
void land();
}
interface IATCMediator
{
public void registerRunway(Runway runway);
public void registerFlight(Flight flight);
public boolean isLandingOk();
public void setLandingStatus( boolean status);
}
class Flight implements Command
{
private IATCMediator atcMediator;
public Flight(IATCMediator atcMediator)
{
this .atcMediator = atcMediator;
}
public void land()
{
if (atcMediator.isLandingOk())
{
System.out.println( "Successfully Landed." );
atcMediator.setLandingStatus( true );
}
else
System.out.println( "Waiting for landing." );
}
public void getReady()
{
System.out.println( "Ready for landing." );
}
}
class Runway implements Command
{
private IATCMediator atcMediator;
public Runway(IATCMediator atcMediator)
{
this .atcMediator = atcMediator;
atcMediator.setLandingStatus( true );
}
@Override
public void land()
{
System.out.println( "Landing permission granted." );
atcMediator.setLandingStatus( true );
}
}
class MediatorDesignPattern
{
public static void main(String args[])
{
IATCMediator atcMediator = new ATCMediator();
Flight sparrow101 = new Flight(atcMediator);
Runway mainRunway = new Runway(atcMediator);
atcMediator.registerFlight(sparrow101);
atcMediator.registerRunway(mainRunway);
sparrow101.getReady();
mainRunway.land();
sparrow101.land();
}
}


输出:

Ready for landing.
Landing permission granted.
Successfully Landed.

有利条件

  • 它限制了子类化。调解人会将原本会分布在多个对象中的行为本地化。改变这种行为只需要子类化中介,同事类就可以按原样重用。

缺点

  • 它集中控制。中介模式以交互的复杂性换取中介中的复杂性。因为中介封装了协议,所以它可能比任何单个同事都复杂。这会使调解人本身成为一个难以维持的整体

本文由 萨凯特·库马尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享