Architectural Design Source: Scenario Analysis of design patterns (1) publish-subscribe

Source: Internet
Author: User
Tags map class

Architectural Design Source: Scenario Analysis of design patterns (1) publish-subscribe
  • Author: poechant
  • Blog: blog.csdn.net/poechant
  • Email: zhongchao.ustc@gmail.com
  • Date: February 24Th, 2012

I have read only the original English (or photocopy) books and some documents on the Internet in terms of design patterns. There are many proprietary terms in the design model. Because I don't know what part of the Chinese translation is, this article is written in English.

1. Motivating scenario

Have you ever encounter such a scenario: the data generatted by someone shoshould be passed to the rest of others or some others in the program, and every extends er has a similar operation?

I think if you have some experience in software programming, there must be such scenarios. in the DP (design pattern) introduced in this article, the data generator or sender is called publisher and the specified er is called subscriber, just as you subscribe
RSS or a local newspaper and the postman sends those newspaper.

2. publisher and subscriber

Here is a publisher interface.subscribeMethod
Is used to register a subscriber to the publisher.publishMethod
Is aimed at sending data to subscribers who have registered before.

// Poechant@CSDNpackage com.sinosuperman.main;public interface Publisher<E> {    public void subscribe(Subscriber<E> subscriber);    public void publish(E data);}

Subscriber interface is as following. The methodgetPublicationIs
Invoked by the publisher to run the specific code implements by the subscribers.

// Poechant@CSDNpackage com.sinosuperman.main;public interface Subscriber<E> {    public void getPublication(E data);}

The natural flow of publish-subscribe Pattern

Publish-subscribe Design Pattern

3. Example

Now we are trying to create a simple command processor, which has some basic functions as ECHO, quit and map.

3.1. class implements publisher
// Poechant@CSDNpackage com.sinosuperman.main;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;public class InputLoop implements Publisher<String> {    private List<Subscriber<String>> subscribers;    private InputLoop() {        subscribers = new ArrayList<Subscriber<String>>();    }    public static InputLoop create() {        return new InputLoop();    }    @Override    //register subscriber    public void subscribe(Subscriber<String> subscriber) {        if (!subscribers.contains(subscriber)) {            subscribers.add(subscriber);        }    }    @Override    // Notify all subscribers    public void publish(String data) {        for (Subscriber<String> sub : subscribers) {            sub.getPublication(data);        }    }    public static String getInput() {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        String response = "";        try {            response = br.readLine();            if (response == null) {                return "";            }        } catch (IOException e) {        }        return response;    }    public void loop() {        while (true) {            System.out.println("> ");            String s = getInput();            publish(s);        }    }}
3.2. Classes implements subscriber

Echo class cocould echo every string you input.

// Poechant@CSDNpackage com.sinosuperman.main;public class Echo implements Subscriber<String> {    private Echo() {    }    public static Echo create() {        return new Echo();    }    @Override    public void getPublication(String data) {        System.out.println("Got: " + data);    }}

Map class cocould return the value according to the key you input.

// Poechant@CSDNpackage com.sinosuperman.main;public class Response implements Subscriber<String> {    private String ifthis;    private String thenthat;    private Response(String it, String tt) {        ifthis = it;        thenthat = tt;    }    public static Response create(String it, String tt) {        return new Response(it, tt);    }    @Override    public void getPublication(String data) {        if (data.equals(ifthis)) {            System.out.println(thenthat);        }    }}

Quit class cocould execute the exit operation, then the program is halted.

// Poecahnt@CSDNpackage com.sinosuperman.main;public class Quit implements Subscriber<String> {    private Quit() {}    public static Quit create() {        return new Quit();    }    @Override    public void getPublication(String data) {        if (data.equals("quit")) {            System.exit(0);        }    }}
3.3. Benchmark

Create an object of inputloop and four subscribers.

package com.sinosuperman.main;public class Test {    public static void main(String[] args) {        InputLoop il = InputLoop.create();        il.subscribe(Echo.create());        il.subscribe(Quit.create());        il.subscribe(Response.create("foo", "bar"));        il.subscribe(Response.create("1+1", "2"));        il.loop();    }}

Test:

> this is a stringGot: this is a string> helpGot: help> fooGot: foobar> 1+1Got: 1+12> fooGot: foobar> quitGot: quit

-

Reprinted please indicate from poechant @ csdn

-

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.