package ru.rpod.taop.visitor;
/**
* @author golodnyj
* @version 0.1
*/
public interface Visitor {
public void visit(Apple v);
public void visit(Bread v);
}
package ru.rpod.taop.visitor;
/**
* @author golodnyj
* @version 0.1
*/
public interface Visitable {
public void accept(Visitor v);
}
package ru.rpod.taop.visitor;
/**
* @author golodnyj
* @version 0.1
*/
public class Apple implements Visitable{
private int price;
public Apple(int price) {
this.price = price;
}
public void accept(Visitor v) {
v.visit(this);
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
package ru.rpod.taop.visitor;
/**
* @author golodnyj
* @version 0.1
*/
public class Bread implements Visitable{
private int price;
public Bread(int price) {
this.price = price;
}
public void accept(Visitor v) {
v.visit(this);
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
package ru.rpod.taop.visitor;
/**
* @author golodnyj
* @version 0.1
*/
public class Calculator implements Visitor {
private double tax;
public void visit(Apple v) {
System.out.println("Посчитали налоги с яблока");
tax = tax + (0.02 * v.getPrice());
}
public void visit(Bread v) {
System.out.println("Посчитали налоги с хлеба");
tax = tax + (0.03 * v.getPrice());
}
public double getTax() {
return tax;
}
}
package ru.rpod.taop.visitor;
import java.util.*;
/**
* @author golodnyj
* @version 0.1
*/
public class ConsoleVisitor {
public static void main(String[] args) {
Collection<Visitable> c = new ArrayList<Visitable>();
c.add(new Apple(10));
c.add(new Apple(10));
c.add(new Bread(10));
c.add(new Apple(10));
c.add(new Bread(10));
c.add(new Bread(10));
c.add(new Apple(10));
Calculator calc = new Calculator();
Iterator iterator = c.iterator();
while (iterator.hasNext()) {
Object o = iterator.next();
if (o instanceof Visitable)
((Visitable) o).accept(calc);
}
System.out.println("tax = " + calc.getTax());
}
}