解码Eclipse架构:IAdaptable-第二部分-简单例子

适配器设计模型 适配器设计模式是怎么在Eclipse中使用?Eclipse平台Runtime有一个很好的例子。 首先,适配器设计模式的背后有一个简单的意图——封装一个对象,让他适用于客服端的其他接口,你可以在我 前面的文章中看到一个简单的适配器意图。 Eclipse中适配器的使用有略微不同和更多重复,在下面的例子,为了简单起见类与接口都放在一个文件中。 下面展现了类的继承关系 

  

当我们想把橘子变成苹果,适配器就来了,下面我们看看他怎么做,在Eclipse中没有重复工作。

interface IAdaptable{
  public Object getAdapter(Class adapter);
}
 
interface IApple extends IAdaptable{ }
 
interface IOrange{ }
 
class Orange implements IOrange{ }
 
interface IPear{ }
 
class Pear implements IPear{ }
 
public class Apple implements IApple{  
  @Override
  public Object getAdapter(Class adapter) {
    //the real story should be forwarding the request to the platform to get adapter
    return PlatformAdapterManager.getAdapter(this, adapter);
  }  
}
 
class PlatformAdapterManager{
  public static Object getAdapter(Object o, Class adapter){
    if(adapter == IOrange.class){
      if(o instanceof Apple){
        return new Orange(); //Read code use an adapter to wrap the apple object and return an adapter object which implements IApple interface
      }
    }else if(adapter == IPear.class){
      if(o instanceof Apple){
        return new Pear();
      }
    }
    return null; //return null when the class does not implement the interface.
  }
}

PlatformAdapterManager 类是完全编造的,Eclipse中事实是platfrom得到一个适配器管理器然后返回一个正确的适配器。

public class Main {  
  public static void main(String args[]){
    IApple apple = new Apple();
    IOrange orange = (IOrange)apple.getAdapter(IOrange.class);
 
    if(orange == null){
      System.out.println("null");
    }else{
      System.out.println(orange);
    }
 
    IPear pear = (IPear)apple.getAdapter(IPear.class);  
    if(pear == null){
      System.out.println("null");
    }else{
      System.out.println(pear);
    }
  }
}

输出

Output:
Orange@4fe5e2c3
Pear@23fc4bec

在类自己内部,这是一个途径实现getAdapter()方法,这个途径不需要注册在类中,因为他已经继承了getAdapter()方法。 以上文章翻译自: http://www.programcreek.com/2011/09/adapters-in-eclipse/

转载于:https://my.oschina.net/markho/blog/498194

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值