前言
本文來自《Head Fist 設計模式》一書的執行個體,這裡僅僅是個人筆記記錄
組合模式
組合模式讓我們能用樹形方式建立對象的結構,其中樹裡面包含了組合以及個别的對象。
故公共基類的方法是一緻,區分在于要不要實作
樹類型基類
包含所有的方法
package composite_pattern;
public abstract class Tree {
public abstract String getName();
public void add(Tree mTree){
throw new UnsupportedOperationException();
}
public Tree getChild(int position){
throw new UnsupportedOperationException();
}
public boolean hasTreeLeaf(){
throw new UnsupportedOperationException();
}
public boolean hasTreeTrunk() {
throw new UnsupportedOperationException();
}
}
上述的方法實作了,但是需要子類進行重寫
樹幹子類
package composite_pattern;
import java.util.ArrayList;
public class TreeTrunk extends Tree {
private ArrayList<Tree> mlist = new ArrayList<>();
@Override
public String getName() {
return TreeTrunk.class.getSimpleName();
}
@Override
public void add(Tree mTree) {
mlist.add(mTree);
}
@Override
public Tree getChild(int position) {
return mlist.get(position);
}
@Override
public boolean hasTreeTrunk() {
return true;
}
@Override
public boolean hasTreeLeaf() {
return true;
}
}
樹葉子類
葉子屬于最終節點,故不需要add(),getChild等方法
package composite_pattern;
public class TreeLeaf extends Tree {
@Override
public String getName() {
return TreeLeaf.class.getSimpleName();
}
@Override
public boolean hasTreeTrunk() {
return false;
}
@Override
public boolean hasTreeLeaf() {
return true;
}
}
結語
感覺這種類似菜單-子菜單設計的樹狀模型還是挺常見的