public class Test {
public static void main(String[] args) {
// 把配套元素提取到一块,与操作对象去耦合
// 吃什么
Home home = new Home();
home.add(new Fruit());
// 让访问者去吃
home.action(new SomeonePerson());
// 配套元素2
Home home2 = new Home();
home2.add(new Fruit());
home2.add(new Vegetable());
// 访问者去吃
home2.action(new OtherPerson());
}
}
// 抽象访问类角色
interface Person {
// 吃水果
void eat(Fruit fruit);
// 吃蔬菜
void eat(Vegetable vegetable);
}
// 抽象元素角色,参数就是访问者对象
interface Food {
// 接收访问者访问
void receive(Person person);
}
// 具体元素角色,访问者具体对这个元素干啥
class Fruit implements Food {
@Override
public void receive(Person person) {
System.out.println("水果维生素");
// 实现双分派
person.eat(this);
}
}
// 具体元素角色,访问者具体对这个元素干啥
class Vegetable implements Food {
@Override
public void receive(Person person) {
System.out.println("蔬菜维生素");
person.eat(this);
}
}
// 具体抽象类对象
class SomeonePerson implements Person {
@Override
public void eat(Fruit fruit) {
System.out.println("某人在吃水果");
}
@Override
public void eat(Vegetable vegetable) {
System.out.println("某人在吃蔬菜");
}
}
// 具体抽象类对象
class OtherPerson implements Person {
@Override
public void eat(Fruit fruit) {
System.out.println("其它人在吃水果");
}
@Override
public void eat(Vegetable vegetable) {
System.out.println("其它人在吃蔬菜");
}
}
// 对象结构类
class Home {
// 集合对象
private List<Food> foodList = new ArrayList<>();
// 添加元素
public void add(Food food) {
foodList.add(food);
}
// 执行
public void action(Person person) {
foodList.forEach(food -> food.receive(person));
}
}
分派:
分为两种:
class Test1{
public static void main(String[] args) {
A a = new B();
a.haha();
}
}
class A {
void haha() {
System.out.println("a");
}
}
class B extends A {
void haha() {
System.out.println("b");
}
}
class Test1{
public static void main(String[] args) {
Test1 test1 = new Test1();
A a = new A();
A b = new B();
A c = new C();
test1.exc(a);
test1.exc(b);
test1.exc(c);
}
void exc(A a) {
System.out.println("a");
}
void exc(B b) {
System.out.println("b");
}
void exc(C c) {
System.out.println("c");
}
}
class Test1{
public static void main(String[] args) {
Test1 test1 = new Test1();
A a = new A();
A b = new B();
A c = new C();
a.re(test1);
b.re(test1);
c.re(test1);
}
void exc(A a) {
System.out.println("a");
}
void exc(B b) {
System.out.println("b");
}
void exc(C c) {
System.out.println("c");
}
}
class A {
void re(Test1 test1){
// 实现双分派(重载+重写)
test1.exc(this);
}
}
class B extends A {
void re(Test1 test1){
// 实现双分派(重载+重写)
test1.exc(this);
}
}
class C extends A {
void re(Test1 test1){
// 实现双分派(重载+重写)
test1.exc(this);
}
}