デザインパターン - composite
【compositeパターンとは】
容器と中身を同じものに扱い、再帰処理が容易にできる。
【compositeパターンのクラス図】
【compositeパターンのメリット】
再帰処理が容易。
【サンプル】
Entry.java |
package composite;
/*
* BoxとItemを同じ物と扱うためのEntryクラス
*/
public interface Entry {
public String getName(); // 名前取得
public int getValue(); // 価格取得
}
|
Box.java |
package composite;
import java.util.List;
/*
* Boxクラス。
* 容器である。
*/
public class Box implements Entry{
private List<Entry> itemList = new ArrayList<Entry>();
private String name;
// private int value;
public Box(String name) {
this.name = name;
//this.value = value;
}
@Override
public String getName() {
return this.name;
}
@Override
// 再帰処理 public int getValue() {
int value = 0;
while(iterator.hasNext()) {
value += iterator.next().getValue();
}
return value;
}
public void add(Entry entry) {
this.itemList.add(entry);
}
}
|
Item.java |
package composite;
/*
* Itemクラス
* 中身 */
public class Item implements Entry{
private String name;
private int value;
public Item(String name, int value) {
this.name = name;
this.value = value;
}
@Override
public String getName() {
return this.name;
}
@Override
public int getValue() {
return this.value;
}
}
|
CompositeTest.java |
package composite;
public class CompositeTest {
public static void main(String[] args) {
Box bigBox = new Box("一番大きいBOX");
Box cdBox = new Box("CD_BOX");
Box bookBox = new Box("BOOK_BOX");
Item cd1 = new Item("CD1", 100);
Item cd2 = new Item("CD2", 200);
Item cd3 = new Item("CD3", 300);
Item book1 = new Item("BOOK1", 1000);
Item book2 = new Item("BOOK2", 2000);
Item book3 = new Item("BOOK3", 3000);
// cdboxにcd1,cd2,cd3を入れる
cdBox.add(cd1);
cdBox.add(cd2);
cdBox.add(cd3);
// bookboxにbook1,book2,book3を入れる
bookBox.add(book1);
bookBox.add(book2);
bookBox.add(book3);
// bigboxにCDBOXとBOOKBOXを入れる
bigBox.add(cdBox);
bigBox.add(bookBox);
System.out.println("CDBOXの総額 : " + cdBox.getValue());
System.out.println("BOOKBOXの総額 : " + bookBox.getValue());
System.out.println("BIGBOXの総額 : " + bigBox.getValue());
}
}
|
結果 |
CDBOXの総額 : 600
BOOKBOXの総額 : 6000
BIGBOXの総額 : 6600
|