Visitor

File Document.java

package tests.Visitor;

interface Document {
    public void accept(Visitor vis);

    public boolean loadFile(String fileName);

    public boolean performOperation(String fileName);
}

File BaseDocument.java

package tests.Visitor;

/**
 *
 * @author jan
 */
public abstract class BaseDocument {
    private String name;
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getName() {
        return this.name;
    }
}

File Visitor.java

package tests.Visitor;

public abstract class Visitor {
    public abstract void visit(Document doc);
}

File HTMLDocument.java

package tests.Visitor;

public class HTMLDocument extends BaseDocument implements Document {

    @Override
    public boolean loadFile(String fileName) {
        System.out.println("loadFile: " + this.getClass().getName());
        return true;
    }

    @Override
    public boolean performOperation(String fileName) {
        System.out.println("performOperation: " + this.getClass().getName());
        return true;
    }

    @Override
    public void accept(Visitor vis) {
        vis.visit(this);
    }

}

File XMLDocument.java

package tests.Visitor;

public class XMLDocument extends BaseDocument implements Document {

    @Override
    public boolean loadFile(String fileName) {
        System.out.println("loadFile: " + this.getClass().getName());
        return true;
    }

    @Override
    public boolean performOperation(String fileName) {
        System.out.println("performOperation: " + this.getClass().getName());
        return true;
    }

    @Override
    public void accept(Visitor vis) {
        vis.visit(this);
    }

}

File WordCounter.java

package tests.Visitor;

public class WordCounter extends Visitor{

    @Override
    public void visit(Document doc) {
        System.out.println("I visit: " + doc.getClass().getSimpleName());
    }
    
}

File main.java

package tests.Visitor;

public class main {
    public static void main(String[] args) {
        BaseDocument[] docs = new BaseDocument[5];
        docs[0] = new XMLDocument();
        ((XMLDocument)docs[0]).setName("doc0");
        docs[1] = new HTMLDocument();
        ((HTMLDocument)docs[1]).setName("doc1");
        docs[2] = new XMLDocument();
        ((XMLDocument)docs[2]).setName("doc2");
        docs[3] = new HTMLDocument();
        ((HTMLDocument)docs[3]).setName("doc3");
        docs[4] = new HTMLDocument();
        ((HTMLDocument)docs[4]).setName("doc4");
        
        WordCounter wordCounter = new WordCounter();
        
        for (int i = 0; i < docs.length; i++) {
            if(docs[i].getClass().getSimpleName().equals("XMLDocument")){
                ((XMLDocument)docs[i]).accept(wordCounter);
            } else if(docs[i].getClass().getSimpleName().equals("HTMLDocument")){
                ((HTMLDocument)docs[i]).accept(wordCounter);
            }
//            System.out.println(docs[i].getName());
        }
    }
}