《图解设计模式》 第六部分 访问数据结构

第十三章 Visotor 模式

public class file extends entry{
  /* 省略 */
  puhblic void accept(Visitor v){
    v.visit(this);
  }
}

public class Main{
  public static void main(String args){
    Directory rootdir = new Dirctory("root");
    /* 省略 */
    rootdir.accept(new ListVisitor());
  }
}

双重分发

这里的 Element accept(Visitory) 和 Visitor的 visit(Element) 他们是相反的关系。前者接受,后者访问。
这种消息分发方式一般被称为 双重分发(double dispatch)

为什么弄这么复杂?

Vistor 模式的目的是将处理的数据从数据结构中分离出来。这里的 ListVisitor 是遍历,我们可能也要做其他事情,比如 文件批量改名之类。所有的行为在 Visitor 的子类中实现就好。

开闭原则(The Open-Closed Principle, OCP)

对扩展是开放的
对修改是关闭的

第14章 Chain of Responsibility 模式

public class Main{
    public static void main(String[] args){
        Support alice = new NoSupport("Alice");
        Support bob = new LimitSupport("Bob", 100);
        Support charlie = new SpecialSupport("Charlie", 429);
        Support diana = new LimitSupport("Diana", 200);
        Support elmo = new OddSupport("Elmo");
        Support fred = new LimitSupport("Fred", 300);

        //设置处理链
        alice.setNext(bob).setNext(charlie).setNext(diana).setNext(elmo).setNext(fred);

        for(int i = 0; i < 500; i += 33){
            alice.support(new Trouble(i));
        }
    }
}


public abstract class Support{
    private Stirntg name;
    private Support next;

    public Support(String name){
        this.name = name;
    }

    public Support setNext(Support next){
        this.next = next;
        return next;
    }

    public final void support(Trouble trouble){
        if(resolve(trouble)){
            done(trouble);
        }else if(next != null){
            next.support(trouble);
        }else{
            fail(trouble);
        }
    }

    protected abstract boolean resolve(Trouble trouble);
    protected void done(Trouble trouble){
        System.out.println(trouble + " is resolved by " + this + ".");
    }

    protected void fail(Trouble trouble){
        System.out.println(trouble + " cannot be resolved.");
    }
}

public class LimitSupport extends Support{
    private int limit;

    public LimitSupport(String name, int limit){
        super(name);
        this.limit = limit;
    }

    protected boolean resolve(Trouble trouble){
        if(trouble.getNumber() < limit){
            return true;
        }else{
            return false;
        }
    }
}

Windows 系统中经常使用这个模式。

posted @ 2024-11-05 10:19  大俗XD  阅读(26)  评论(0)    收藏  举报