, , - . factory, . , , . .
Plant banana = ...;
Plant spinach = ...;
Weigher<Plant> bananaWeigher = WeigherFactory.getInstance(banana);
bananaWeigher.weigh(spinach);
- WeigherFactory Plant , WeigherFactory. ,
public class WeigherFactory {
public static BananaWeigher getInstance(Banana banana) {
return new BananaWeigher();
}
public static SpinachWeigher getInstance(Spinach spinach) {
return new SpinachWeigher();
}
}
public abstract class FactoryUser<P extends Plant> {
public abstract Weigher<P> getWeigher(P plant);
public void run(P plant) {
Weigher<P> weigher = getWeigher(plant);
int weight = weigher.weigh(plant);
System.out.println("the plant weighs: " + weight);
}
}
public class Main {
public static void main(String[] args) {
Banana banana = new Banana();
FactoryUser<Banana> factoryUser = new FactoryUser<Banana>() {
@Override
public BananaWeigher getWeigher(Banana banana) {
return WeigherFactory.getInstance(banana);
}
};
factoryUser.run(banana);
}
}
( )
PlantWeigher, , Plant. . , . , .
Visitor , , . .
public interface Visitor<T> {
public T visit(Banana banana);
public T visit(Spinach spinach);
}
public class WeighingVisitor implements Visitor<Integer> {
@Override
public Integer visit(Banana banana) {
return banana.getBananaWeight();
}
@Override
public Integer visit(Spinach spinach) {
return spinach.getSpinachWeight();
}
}
public class PlantWeigher {
public int weigh(Plant plant) {
return plant.accept(new WeighingVisitor());
}
}
-, Plant, , Visitor. Plant .
public interface Plant {
public <T> T accept(Visitor<T> visitor);
}
public class Banana implements Fruit {
private int weight;
public Banana(int weight) {
this.weight = weight;
}
public int getBananaWeight() {
return weight;
}
@Override
public <T> T accept(Visitor<T> visitor) {
return visitor.visit(this);
}
}
, :
List<Plant> plants = asList(new Banana(10), new Spinach(20));
PlantWeigher weigher = new PlantWeigher();
int weight = 0;
for (Plant p : plants) {
weight += weigher.weigh(p);
}
System.out.println("total weight: " + weight);
Dunes source
share