本文共 2626 字,大约阅读时间需要 8 分钟。
尚硅谷视频连接https://www.bilibili.com/video/BV1G4411c7N4?from=search&seid=11487053970269878470
1.定义活动
public abstract class Action { //得到男性 的测评 public abstract void getManResult(Man man); //得到女性 的测评 public abstract void getWomanResult(Woman man);}
2.定义人
public abstract class Person { //提供一个方法,让访问者可以访问 public abstract void accept(Action action);}
3.对人进行实现
public class Man extends Person { @Override public void accept(Action action) { action.getManResult(this); }}//=========================================public class Woman extends Person { @Override public void accept(Action action) { action.getWomanResult(this); }}
4.活动的实现—具体状态
public class Success extends Action { @Override public void getManResult(Man man) { System.out.println("男人给的评价是成功"); } @Override public void getWomanResult(Woman man) { System.out.println("女人给的评价是成功"); }}//===========================================public class Fail extends Action { @Override public void getManResult(Man man) { System.out.println("男人给的评价是失败"); } @Override public void getWomanResult(Woman man) { System.out.println("女人给的评价是失败"); }}
5.对象结构,对象管理
public class ObjectStructure { //维护了一个集合 private Listpersons = new LinkedList<>(); //添加到list public void attach(Person p) { persons.add(p); } //移除 public void detach(Person p) { persons.remove(p); } //显示测评情况 public void display(Action action) { for (Person person : persons) { person.accept(action); } }}
6.客户端
public static void main(String[] args) { //创建ObjectStructure ObjectStructure objectStructure = new ObjectStructure(); objectStructure.attach(new Man()); objectStructure.attach(new Woman()); //成功 Success success = new Success(); objectStructure.display(success); System.out.println("==================="); //失败 Fail fail = new Fail(); objectStructure.display(fail);}
双分派,所谓的双分派是指不管类怎么变化,我们都能找到期望的方法运行
双分派意味着得到执行的操作取决于请求的种类和两个接收者的类型
由以上实例,假设我们要添加一个Wait的状态类,考察Man类和Woman类的反应,由于使用了双分派,只需增加一个Action子类,在客户端调用即可,不需要修改任何其他类的代码
转载地址:http://hlbcz.baihongyu.com/