Thread:
 Simpler solution with a PoliticianVisitorCollector 
 astedile   23 Feb 2007, 06:41 

Comment
Prev. thread 
 Next thread
 
Prev. posting 
 Next posting
From: astedile (23 Feb 2007, 06:41) Replies: 0, Views: 12322
Subject: Simpler solution with a PoliticianVisitorCollector
This solution is simpler and it seems to work for me. One advantage is, 
that the individual politicians need not be listed in the visitor. I 
checked and saw that the returned objects and their classes are OK.

I implement a specialized <code>PoliticianVisitorCollector</code>. It 
takes any kind of collection and adds one Politician of correct sub-
class instance on each call to abstract <code>accept()</code> method. 
So I can convert a collection of proxies to a collection of polymorphic 
instances.

<code>
public interface PoliticianVisitor {
    void visit(Politician p);
}

public class PoliticianVisitorCollector implements PoliticianVisitor {

    private Collection<Politician> politicians;

    public PoliticianVisitorCollector(Collection<Politician> 
collection) {
        politicians = collection;
    }

    public void visit(Politician p) {
        politicians.add(p);
    }
}

public abstract class Politician {
    ...
    public abstract void accept(PoliticianVisitor visitor);
}

public class Republican extends Politician {
    ...
    @Override
    public void accept(PoliticianVisitor visitor) {
        visitor.visit(this);
    }
}

public class Democrat extends Politician {
    ...
    @Override
    public void accept(PoliticianVisitor visitor) {
        visitor.visit(this);
    }
}
</code>

Test example:

<code>
public class PoliticianVisitorCollectorTest extends TestCase {

    public void testVisit() throws Exception {
        List<Politician> politiciansOut = new ArrayList<Politician>(2);
        PoliticianVisitorCollector visitor = new 
PoliticianVisitorCollector(politiciansOut);

        List<Politician> politiciansIn = Arrays.asList(new 
Republican(), new Democrat());
        for (Politician politician : politiciansIn) {
            politician.accept(visitor);
        }

        assertEquals("Republican", 
politiciansOut.get(0).getClass().getSimpleName());
        assertEquals("Democrat", 
politiciansOut.get(1).getClass().getSimpleName());
        assertEquals(2, politiciansOut.size());
    }
}
</code>

I tried the same with a <code>public void getThis()</code> method 
instead of the <code>accept()</code>. This did not work.

Hope this helps.
Prev. thread 
 Next thread
 
Prev. posting 
 Next posting
© Copyright 2006, Red Hat Middleware, LLC. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc. [Privacy Policy]