UML
状态 相当于访问者
public abstract class Action {
public abstract void getManConclusion(Man man);
public abstract void getWomanConclusion(Woman woman);
}
成功的状态
public class Success extends Action {
@Override
public void getManConclusion(Man man) {
System.out.println("男人成功时,背后多半有一个伟大的女人");
}
@Override
public void getWomanConclusion(Woman woman) {
System.out.println("女人成功时,背后大多有一个不成功的男人");
}
}
失败的状态
public class Failing extends Action {
@Override
public void getManConclusion(Man man) {
System.out.println("男人失败时,闷头喝酒,谁也不用劝");
}
@Override
public void getWomanConclusion(Woman woman) {
System.out.println("女人失败时,眼泪汪汪,谁也劝不了");
}
}
人 被访问的对象
public abstract class Person {
public abstract void accept(Action action);
}
男人
public class Man extends Person {
@Override
public void accept(Action action) {
action.getManConclusion(this);
}
}
女人
public class Woman extends Person {
@Override
public void accept(Action action) {
action.getWomanConclusion(this);
}
}
对象结构类
import java.util.ArrayList;
import java.util.List;
public class ObjectStructure {
private List<Person> people = new ArrayList<>();
public void add(Person person) {
people.add(person);
}
public void remove(Person person) {
people.remove(person);
}
public void disPlay(Action action) {
for (Person person : people) {
person.accept(action);
}
}
}
测试类
public class Main {
public static void main(String[] args) {
ObjectStructure objectStructure = new ObjectStructure();
objectStructure.add(new Man());
objectStructure.add(new Woman());
Success success = new Success();
objectStructure.disPlay(success);
Failing failing = new Failing();
objectStructure.disPlay(failing);
}
}
运行结果