中介者模式
Posted yuanGrowing
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了中介者模式相关的知识,希望对你有一定的参考价值。
一、作用:降低类与类之间的耦合程度,当A和B有双向的关系时,就产生了较强的耦合,这时候引入一个中介者的类,A与B都只和这个中介者类相关,由中介者类来控制A与B的关系,这样就完成了解耦。
二、例子:
有两种工人workera 和workerb,他们需要一起工作,如果不使用中介者模式,那么就需要两个类,WorkerA和WorkerB,他们之间相互依赖。使用中介者模式时,如下:
先定义一个抽象工作类:
public abstract class AbstractWorker
IMediator mediator ;
public AbstractWorker(IMediator mediator)
this.mediator = mediator ;
abstract void work();
WorkerA:
public class WorkerA extends AbstractWorker
public WorkerA(IMediator mediator)
super(mediator);
@Override
void work()
System.out.println("worka is working!");
WorkerB:
public class WorkerB extends AbstractWorker
public WorkerB(IMediator mediator)
super(mediator);
@Override
void work()
System.out.println("workb is working");
IMediator接口:
public abstract class AbstractWorker
IMediator mediator ;
public AbstractWorker(IMediator mediator)
this.mediator = mediator ;
abstract void work();
Mediator实现类:
public class Mediator implements IMediator
private WorkerA workera ;
private WorkerB workerb ;
@Override
public void createWorkers(WorkerA workerA,WorkerB workerB)
this.workera = workerA ;
this.workerb = workerB ;
@Override
public void beginWork()
this.workera.work();
this.workerb.work();
测试类:
public class Test
public static void main(String[] args)
IMediator mediator = new Mediator();
WorkerA workerA = new WorkerA(mediator);
WorkerB workerB = new WorkerB(mediator);
mediator.createWorkers(workerA, workerB);
mediator.beginWork();
运行结果:
worka is working!
workb is working
以上是关于中介者模式的主要内容,如果未能解决你的问题,请参考以下文章