請問版主所說的Adapter模式的問題????

tanmingbo發表於2003-10-15
版主你好,我看了你所寫的介面卡模式Adapter前部分,SquarePeg、RoundPeg、PegAdapter,我感到疑惑的是,如果我要在PegAdapter中實現既要打方型樁,又要打圓形樁的問題,怎麼實現好呢?在PegAdapter中重寫了insert類實現打圓形樁的問題,因此,如果要打方型樁的話,應該有這句:SquarePeg squ=new SquarePeg().但是如此一來的話,我就體會不出介面卡的好處了。我感到還不如在應用中直接定義SquarePeg、RoundPeg的例項呼叫各自的方法,或者在PegAdapter中採用組合的方式將SquarePeg、RoundPeg包含近來,或者對PegAdapter類作如下改寫:
public class PegAdapter extends SquarePeg {
private RoundPeg roundPeg;
public PegAdapter(RoundPeg peg) { this.roundPeg=peg; }
public void insertIntoHole(String str) {
roundPeg.insertIntoHole(str);
}
}
即不重寫SquarePeg中的insert方法。這樣,在PegAdapter類中即可以呼叫
insert()方法打圓型樁,又可以呼叫insertIntoHole()方法打方型樁。

相關文件在本站“設計模式”中!

以上是我個人的理解,懇請各位同行指正!
我的QQ:15477736,MSN:tan_mingbo@hotmail.com


相關文章