Last active
November 14, 2019 17:38
-
-
Save mtov/d447fd22974c57688d0fd109cb9509ea to your computer and use it in GitHub Desktop.
Visitor (Design Patterns)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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