简体   繁体   中英

About colleague in mediator design pattern?

I know the purpose of mediator pattern is that each colleague don't have to know each other to communicate with each other. All colleagues just know about the mediator.

Design patterns are not for specific language, but my question is specific to Java.

I want to put a field of subclass to the superclass, but in java there will be some problems:

  • In Java, all fields in interface are public static final , and it's also not a good practice to use such fields. ( Why )

  • If I put the reference to the mediator in the interface Colleague , then each concrete colleague can't change its mediator in the runtime since it is final:

     interface Colleague { Mediator mediator; // Which is public static final } 

    So in the program,

     { // ... colleague.changeMediator(newMediator); // this is impossible. // ... } 

    .

  • As the structure below, the colleague is an abstract class instead. Then this pattern would not be useful since the concrete colleague may already inherit some other class, and multiple inheritance is not allowed in Java.

    Foo can't be a concrete colleague since it already inherited Bar.

     public class Foo extends Bar, Colleague { // this is impossible. // ... } 

If there is no way to put the reference to mediator in the interface Colleague, the solutions I've thought of are:

  1. As this example , remove the reference. Assume that there is no need to keep a reference to mediator. (Would this cause any problem?)

  2. Just define a reference for each concrete colleague. (But this means code repetition.)

  3. As the example of design-patterns-stories.com , let the colleague be abstract and accept the fact that no-one will extend the Colleague.

The structure of mediator pattern (from design-patterns-stories.com ): 来自http://www.design-patterns-stories.com/patterns/Mediator/的调解器模式

There's 2 things you can do.

  • Define Colleague to be a generic that extends Mediator so you'd have public class Colleague<? extends Mediator> public class Colleague<? extends Mediator>

  • Don't inherit from Mediator even though the pattern calls for it. Just pass it in as argument and call notifications on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM