访问者模式

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();
		}
	}
}


如何理解双重分派?
 

你可能感兴趣的:(java,C++,c,C#)