完成一个测评系统需求

将不同的观众分为不同的类,然后每个类里面实现评价的功能


/***
* @author shaofan
* @Description 访问者模式解决评测需求
*/
public class Visitor {
public static void main(String[] args) {
ObjectStructure objectStructure = new ObjectStructure();
objectStructure.attach(new Man());
objectStructure.attach(new Woman());
objectStructure.display(new Success());
}
}
abstract class Action{
abstract void getManResult(Man man);
abstract void getWomanResult(Woman woman);
}
class Success extends Action{
@Override
void getManResult(Man man) {
System.out.println("男人"+man.getName()+"觉得成功");
}
@Override
void getWomanResult(Woman woman) {
System.out.println("女人"+woman.getName()+"觉得成功");
}
}
class Fail extends Action{
@Override
void getManResult(Man man) {
System.out.println("男人"+man.getName()+"觉得失败");
}
@Override
void getWomanResult(Woman woman) {
System.out.println("女人"+woman.getName()+"觉得失败");
}
}
abstract class Person{
String name = "匿名";
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
abstract void accept(Action action);
}
class Man extends Person{
@Override
void accept(Action action) {
action.getManResult(this);
}
}
/***
* 这里使用到双分派,首先将操作作为参数传递到类中,然后调用操作方法时,再将自身对象传递到操作中
*/
class Woman extends Person{
@Override
void accept(Action action) {
action.getWomanResult(this);
}
}
class ObjectStructure{
private List<Person> persons = new LinkedList<>();
public void attach(Person person){
persons.add(person);
}
public void detach(Person person){
persons.remove(person);
}
public void display(Action action){
for (Person person : persons) {
person.accept(action);
}
}
}