Skip to content

Instantly share code, notes, and snippets.

@kenpusney
Last active October 23, 2018 10:50
Show Gist options
  • Save kenpusney/86ea88318625b2b7399291954bd970f1 to your computer and use it in GitHub Desktop.
Save kenpusney/86ea88318625b2b7399291954bd970f1 to your computer and use it in GitHub Desktop.
Visitor
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
interface Freight {
void accept(FreightVisitor visitor);
}
interface FreightVisitor {
default void visit(Freight freight) {
}
default void visit(FixedFreight freight) {
this.visit((Freight) freight);
}
default void visit(ByPriceFreight freight) {
this.visit((Freight) freight);
}
default void visit(ByWeightFreight freight) {
this.visit((Freight) freight);
}
}
@Data
class FixedFreight implements Freight {
int freight;
@Override
public void accept(FreightVisitor visitor) {
visitor.visit(this);
}
}
@Data
class ByPriceFreight implements Freight {
int start = 0;
int startLimit = 0;
int priceUnit;
int freightPerUnit;
@Override
public void accept(FreightVisitor visitor) {
visitor.visit(this);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class ByWeightFreight implements Freight {
int start = 0;
int startLimit = 0;
int weightLimit;
int freightPerUnit;
@Override
public void accept(FreightVisitor visitor) {
visitor.visit(this);
}
}
@Data
class ByWeightCalculateVisitor implements FreightVisitor {
int weight;
int freight = 0;
ByWeightCalculateVisitor(int weight) {
this.weight = weight;
}
@Override
public void visit(ByWeightFreight freight) {
this.freight = // do the calculation
}
}
public class App {
public static void main(String[] args) {
ByWeightCalculateVisitor visitor = new ByWeightCalculateVisitor(10);
ByWeightFreight byWeightFreight = new ByWeightFreight(0, 0, 10, 10);
byWeightFreight.accept(visitor);
System.out.println(visitor.getFreight());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment