public int getPrice() {
int total = 0;
for ( int i = 0; i < items.length; i++ ) {
total += items[i].getPrice();
}
return total;
}
}
バリューセットを注文するときは、次のようになります。
public class Fish() implements Item { ... }
// ポテト等、サイズの別があるものは、コンストラクタでサイズを指定
// させるという設計もあるが、ここでは単純に PotatoM().
public class PotatoM() implements Item { ... }
public class Cola() implements Item { ... }
reg.orderItem( new ValueSet( new Fish(), new PotatoM(), new Cola() ) );
getPrice() メソッド内の「return total;」の前に次のコードを追加すれば、
if ( items[1] instanceof PotatoL ) {
total += 30;
}
「バリューセットを注文している場合は +30 円でポテトをLサイズにできる」、という処理を実装できます。あとは、バリューセットを注文するときに、ValueSet の第二引数を new PotatoM() ではなく PotatoL() にするだけです。
reg.orderItem( new ValueSet( new Fish(), new PotatoL(), new Cola() ) );
public int getPrice() {
int total = items[0] + items[2];
if ( items[1] instanceof PotatoL ) {
total += new PotatoM().getPrice() + 30;
}
else {
total += itesm[1]; // PotatoM
}
}