2

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): Mediator pattern from http://www.design-patterns-stories.com/patterns/Mediator/

Community
  • 1
  • 1
Kindred
  • 1,229
  • 14
  • 41
  • You're talking about "the field", "this change", etc. But you didn't post any line of code, so I can't understand anything to what you're asking. – JB Nizet May 08 '17 at 13:52

1 Answers1

0

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>

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

jiveturkey
  • 2,484
  • 1
  • 23
  • 41