Observer

File Constants.java

package tests.Observer;

public class Constants {
    public static final String MESSAGE_SAVE_DOCUMENT = "MESSAGE_SAVE_DOCUMENT";
    public static final String MESSAGE_XML_DOCUMENT_SAVED = "MESSAGE_XML_DOCUMENT_SAVED";
    public static final String MESSAGE_TXT_DOCUMENT_SAVED = "MESSAGE_TXT_DOCUMENT_SAVED";
}

File MessageSender.java

package tests.Observer;

public interface MessageSender {

    void message(String msg, String data);

}

File Messages.java

package tests.Observer;

import java.util.ArrayList;
import java.util.List;

public class Messages {

    private static final List<MessageSender> listeners = new ArrayList<MessageSender>();
    private static Messages instance = null;

    private Messages() {

    }
    
    public static Messages getInstance() {
        if (instance != null) {
            return instance;
        } else {
            instance = new Messages();
            return instance;
        }
    }
    
    public void addListener(MessageSender listener) {
        listeners.add(listener);
    }
    
    public void Send(String message, String data) {
        for(MessageSender listener : listeners){
            listener.message(message, data);
        }
    }
}

File TxtDocument.java

package tests.Observer;

public class TxtDocument implements MessageSender {

    public TxtDocument() {
    }

    @Override
    public void message(String msg, String data) {
        if(msg.equals(Constants.MESSAGE_SAVE_DOCUMENT)) {
            System.out.println("TxtDocument: " + msg);
            main.messages.Send(Constants.MESSAGE_TXT_DOCUMENT_SAVED, data);
        }
    }
    
}

File XmlDocument.java

package tests.Observer;

public class XmlDocument implements MessageSender{

    public XmlDocument() {
    }

    @Override
    public void message(String msg, String data) {
        if(msg.equals(Constants.MESSAGE_SAVE_DOCUMENT)) {
            System.out.println("XmlDocument: " + msg);
            main.messages.Send(Constants.MESSAGE_XML_DOCUMENT_SAVED, data);
        } else if (msg.equals(Constants.MESSAGE_XML_DOCUMENT_SAVED)) {
            System.out.println("XML SAVED!");
        }
    }
    
}

File main.java

package tests.Observer;

public class main {

    public static final Messages messages = Messages.getInstance();

    public static void main(String[] args) {
        XmlDocument xml = new XmlDocument();
        TxtDocument txt = new TxtDocument();
        
        messages.addListener(txt);
        messages.addListener(xml);
        
        messages.Send(Constants.MESSAGE_SAVE_DOCUMENT, null);
        
    }
}