Tuesday, 19 April 2016

Mediator pattern - Example


If you have a complex GUI, whenever a button has been clicked, the related actions should be disabled or enabled. You may design a Mediator class to include all related classes : 

interface Command {
    void execute();
}

class Mediator {
    BtnView btnView;
    BtnSearch btnSearch;
    BtnBook btnBook;
    LblDisplay show;

    //....
    void registerView(BtnView v) {
        btnView = v;
    }
    void registerSearch(BtnSearch s) {
        btnSearch = s;
    }
    void registerBook(BtnBook b) {
        btnBook = b;
    }
    void registerDisplay(LblDisplay d) {
        show = d;
    }
    void book() {
       btnBook.setEnabled(false);
       btnView.setEnabled(true);
       btnSearch.setEnabled(true);
       show.setText("booking...");
    }
    void view() {
       btnView.setEnabled(false);
       btnSearch.setEnabled(true);
       btnBook.setEnabled(true);
       show.setText("viewing...");
    }
    void search() {
       btnSearch.setEnabled(false);
       btnView.setEnabled(true);
       btnBook.setEnabled(true);
       show.setText("searching...");
    }
}

Then, you may define classes which should be controlled by the Mediator class.
class BtnXYZ extends JButton implements Command {
    Mediator med;
    BtnXYZ(ActionListener al, Mediator m) {
        super("View");
        // super("Search");
        // super("Book");
        addActionListener(al);
        med = m;
        med.registerView(this);
        // med.registerSearch(this);
        // med.registerBook(this);
    }
    public void execute() {
       med.view();
       // med.search();
       // med.book();
    }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.