import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class Mainer {
public static void main(String[] args) {
List flowers = new ArrayList();
for (int i = 0; i < 10; i++) {
flowers.add(FlowerGenerator.newFlower());
}
Visitor vist = new StringVistor();
Iterator it = flowers.iterator();
while (it.hasNext()) {
((Flower) it.next()).accept(vist);
System.out.println(vist);
}
}
}
interface Flower {
void accept(Visitor v);
}
interface Visitor {
void visit(Gladiolus g);
void visit(Runuculus r);
void visit(Chrysanthemum c);
}
class StringVistor implements Visitor {
String s;
public String toString() {
return s;
}
public void visit(Gladiolus g) {
s = "Gladiolus";
}
public void visit(Runuculus r) {
s = "Runuculus";
}
public void visit(Chrysanthemum c) {
s = "Chrysanthemum";
}
}
class BeeVistor implements Visitor {
public void visit(Gladiolus g) {
System.out.println("Bee and Gladiolus");
}
public void visit(Runuculus r) {
System.out.println("Bee and Runuculus");
}
public void visit(Chrysanthemum c) {
System.out.println("Bee and Chrysanthemum");
}
}
class Gladiolus implements Flower {
public void accept(Visitor v) {
v.visit(this);
}
}
class Runuculus implements Flower {
public void accept(Visitor v) {
v.visit(this);
}
}
class Chrysanthemum implements Flower {
public void accept(Visitor v) {
v.visit(this);
}
}
class FlowerGenerator {
private static Random rand = new Random();
public static Flower newFlower() {
switch (rand.nextInt(3)) {
default:
case 0:
return new Gladiolus();
case 1:
return new Runuculus();
case 2:
return new Chrysanthemum();
}
}
}
如何理解双重分派?
访问者模式
最新推荐文章于 2024-10-02 21:12:17 发布
本文通过一个具体的Java示例,展示了双重分派设计模式的应用。该模式允许基于发送消息的对象类型和接收消息的对象类型来选择方法实现。示例中定义了花的抽象接口和访问者接口,并实现了多种花的具体类及不同的访问者类。
摘要由CSDN通过智能技术生成