adapter另外一段代码,如下,WhatIHave是已经有的类,是adaptee,是将要被适配的对象,WhatIWant是是需要,是需求,试图使用Adapter模式达到这个需求,WhatIUse是客户端,表示客户端将如何使用WhatIWant。
客户端WhatIUse是希望实现WhatIWant的f方法,但是我们目前资源只有WhatIHave,那么通过Adapter模式来转换它,ProxyAdapter就是将WhatIHave转变为WhatIWant,就类似,日本带来一个笔记本,需要110V,中国都是220V,怎么办,使用变压器将220V转换为110V。
WhatIWant的f方法内容实现是根据需要,这里是
whatIHave.g();
whatIHave.h();
当然,也可以写成:
whatIHave.g();
或
whatIHave.h();
如何写,取决于实际需要,这已经不在模式定义范围之内。
class WhatIHave {
public void g() {}
public void h() {}
}
interface WhatIWant {
void f();
}
class ProxyAdapter implements WhatIWant {
WhatIHave whatIHave;
public ProxyAdapter(WhatIHave wih) {
whatIHave = wih;
}
public void f() {
// Implement behavior using
// methods in WhatIHave:
whatIHave.g();
whatIHave.h();
}
}
class WhatIUse {
public void op(WhatIWant wiw) {
wiw.f();
}
}