Wzorce projektowe: Mediator

Wzorzec operacyjny Mediator jest wykorzystywany do skupiania złożonych procedur komunikacji i sterowania w środowisku powiązanych obiektów. Obiekty w systemie zamiast komunikować się między sobą bezpośrednio robią to poprzez klasę Mediatora – nie muszą wtedy wiedzieć o swoim własnym istnieniu bezpośrednio. Wysyłają informację do mediatora, a on przekaże go do obiektu, który ma być celem żądania. Pozwala to na łatwą przyszłą modyfikację aplikacji, ponieważ wszystkie wpólne relacje są w jednym miejscu.

Sprawdźmy działanie programu, który oddziela obiekt wysyłający informacje, od obiektu który jest odbiorcą tych wiadomości.

 1 public class Mediator {
 2     private boolean slotFull = false;
 3
 4     private int number;
 5
 6     public synchronized void storeMessage(int num) {
 7         while (slotFull == true) {
 8             try {
 9                 wait();
10             } catch (InterruptedException e) {
11                 e.printStackTrace();
12             }
13         }
14
15         slotFull = true;
16         number = num;
17         notifyAll();
18
19     }
20
21     public synchronized int retrieveMessage() {
22
23         while (slotFull == false)         
24
25             try {
26                 wait();
27             } catch (InterruptedException e) {
28             }
29
30         slotFull = false;
31
32         notifyAll();
33
34         return number;
35
36     }
37 }
38 
 1 class Producer extends Thread {
 2
 3     private Mediator med;
 4
 5     private int id;
 6
 7     private static int num = 1;
 8
 9     public Producer(Mediator m) {
10         med = m;
11         id = num++;
12     }
13
14     public void run() {
15
16         int num;
17
18         while (true) {
19
20             med.storeMessage(num = (int) (Math.random() * 100));
21
22             System.out.println("p" + id + "-" + num + "   ");
23
24         }
25     }
26 }
 1 class Consumer extends Thread {
 2
 3     private Mediator med;                
 4
 5     private int id;                 
 6
 7     private static int num = 1;
 8
 9     public Consumer(Mediator m) {
10         med = m;
11         id = num++;
12     }
13
14     public void run() {
15
16         while (true) {
17
18             System.out.println("c" + id + "-" + med.retrieveMessage() + "   ");
19
20         }
21     }
22 }
 1 class MediatorDemo {
 2
 3     public static void main(String[] args) {
 4
 5         Mediator mb = new Mediator();
 6
 7         new Producer(mb).start();
 8
 9         new Producer(mb).start();
10
11         new Consumer(mb).start();
12
13         new Consumer(mb).start();
14
15         new Consumer(mb).start();
16
17         new Consumer(mb).start();
18
19     }
20 }

Diagram wzorca:

  • Wykop
  • Blip
  • Twitter
  • Facebook
  • DZone
  • Digg
  • Blinklist
  • Delicious
  • Evernote
  • LinkedIn
  • Google Bookmarks
  • Google Buzz
  • Google Reader
  • Share/Bookmark

Podobne wpisy:

Leave a Reply