ITeye博客

Adapter模式(Class Adapter)

Ozone · 2008-05-05 23:07 · 设计模式 · 企业架构 · Markdown

昨天讨论了Adapter模式的一种情况Object Adapter,他比较适用于某些时候的二次开发,但我们拿到某一个组件的class文件,没有源码,只有功能列表的情况时,某些时候整合需要Object adapter。Adapter还有另外一种情况 Class Adapter。 我们现在的程序使用接口 PutBags


public interface PutBags {
  public void putAllBags();
}

如果我们有一个类的class文件PutFootBall,而无法适用其源码。只能适用其中的putAllFootBall()方法。


public class PutFootBall {
  public void putAllFootBall(){
    System.out.println("Put Football....");
  }
}

而在我们现有的程序所适用的方式是


public class Put implements PutBags{
  public void putAllBags(){
    System.out.println("Realize method....");
  }
  public void putOther(){
    System.out.println("Other....");
  }
}

如果我们现在不想改变PutBags接口,并且不希望改变PutAllFootBall()此时

我们考虑,如何让Put类既有第三方类的功能,又不改变原有的接口继承?简

单的讲,要想某个类拥有其他的类的功能继承是最普遍的方法。所以我们使用

继承并实现的方式


public class Put extends PutFootBall implements PutBags{
  public void putAllBags(){
    putBall();  
}
}

评论(3)

  1. #3 楼 · bloodrate · 2008-06-11 10:26

    我觉得不如改成这样:

    public class Put implements PutBags{ PutFootBall pb = new PutFootBall() public void putAllBags(){
    putBall();
    }
    public void putAllFootBall(){ pb.putAllFootBall(); } }

    我总觉得adapter最佳用处是用来实现某些类接口不统一的情况得

  2. #2 楼 · xql80329 · 2008-06-03 17:00

    putBall(); 哪儿呢?

  3. #1 楼 · zong2007 · 2008-05-11 15:20

    嗯,不错,刚好温习下设计模式,共享下

评论功能维护中,当前仅展示历史评论。