解决的办法是:在EntityModel中不用 implements Ibodyinfo。而是实现getAdapter方法:
public Object getAdapter(Class adapter){ if(adapter==Ibodyinfo.class) return new BodySource(this); return null; }
其中BodySource的代码如下;
package com.wjy.understandinterface; public class BodySource implements Ibodyinfo { EntityModel model; public BodySource(EntityModel model) { this.model = model; } @Override public double getHeight() { // TODO Auto-generated method stub return model.height; } @Override public double getWeight() { // TODO Auto-generated method stub return model.weight; } }
这样就可以在Main函数中这样获得height和weight信息了:
Ibodyinfo bodyinfo=(Ibodyinfo)((new EntityModel("wangjiyuan",22,177.00,74.00)).getAdapter(Ibodyinfo.class)); bodyinfo.getHeight(); bodyinfo.getWeight();
注意以上的 (new EntityModel("wangjiyuan",22,177.00,74.00)).getAdapter(Ibodyinfo.class)执行之后 会返回一个 BodySource的对象,而BodySource实现了Ibodyinfo接口,所以可以将其转化成Ibodyinfo,类似于 接口引用指向实现其的类的对象。相当于把 处理height和weight的代码放在了BodySource类中,而BodySource和EntityModel是聚合关系,通过
return new BodySource(this);中的this将EntityModel对象传给了BodySource中聚合的EntityModel引用。