Skip to content

Instantly share code, notes, and snippets.

@mtov

mtov/Main.java

Last active Nov 14, 2019
Embed
What would you like to do?
Visitor (Design Patterns)
import java.util.ArrayList;
import java.util.List;
abstract class Veiculo {
private String placa;
public Veiculo(String placa) {
this.placa = placa;
}
public String getPlaca() {
return placa;
}
abstract public void accept(Visitor v);
}
class Carro extends Veiculo {
public Carro (String placa) {
super(placa);
}
public void accept(Visitor v) {
v.visit(this);
}
}
class Onibus extends Veiculo {
public Onibus (String placa) {
super(placa);
}
public void accept(Visitor v) {
v.visit(this);
}
}
interface Visitor {
void visit(Carro c);
void visit(Onibus o);
}
class PrintVisitor implements Visitor {
public void visit(Carro c) {
System.out.println("Carro: " + c.getPlaca());
}
public void visit(Onibus o) {
System.out.println("Onibus: " + o.getPlaca());
}
}
public class Main {
public static void main(String[] args) {
List<Veiculo> list = new ArrayList<Veiculo>();
list.add(new Carro("C1"));
list.add(new Onibus("O1"));
list.add(new Carro("C2"));
list.add(new Onibus("O2"));
PrintVisitor visitor = new PrintVisitor();
for (Veiculo veiculo: list) {
// visitor.visit(veiculo); erro de compilação (Java não possui double dispatch)
veiculo.accept(visitor);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.