Imagine the following situation: I want to create a bidding application (e.g. ebay) with a composite design pattern
I am creating an abstract superclass, such as "BidComponent" (which has getName ()) and two subclasses of "Article" and "Category".
There is a list in the category that may contain other BidComponents, the article does not implement List, but the getPrice () method.
If I want to iterate over this structure and want to print the structure-article, I need an instance:
if(element instanceof Article){
Article article = (Article)element;
System.out.println(article.getName() + ":" + article.getPrice());
}else{
Category category = (Category)element;
System.out.println(category.getName());
}
This seems to me wrong. Is there a better way to implement this (So without checking the type through instanceof)? I ask this question because I read several times that using instanceof is a bad design ...
// Edit to mention my problem with visitors:
Ok. , . ,
public class HighestBidVisitor implements BidComponentVisitor{
private double highestBid = 0d;
public HighestBidVisitor(Category category){
visitCategory(category);
}
@Override
public void visitCategory(Category category){
Iterator<BidComponent> elementsIterator = category.iterator();
while(elementsIterator.hasNext()){
BidComponent bidComponent = elementsIterator.next();
if(bidComponent instanceof Article) visitArticle((Article)bidComponent);
else visitCategory((Category)bidComponent);
}
}
@Override
public void visitArticle(Article article){
if(article.getPrice() > highestBid) highestBid = article.getPrice();
}
}
(. visitCategory). ?