私は食事を作るレストランを持っています。キッチンには、消費者向けのプレートが用意されています。PECS:コンシューマをプロデューサに変換する方法は?
class Food{}
class Bamboo extends Food {}
interface Kitchen {
void build(List<? super Food> dessert);
}
abstract class Restaurant {
Kitchen kitchen;
public Restaurant(Kitchen kitchen) {
this.kitchen = kitchen;
}
List<? extends Food> getMeals() {
List<Food> food = new ArrayList<>();
this.kitchen.build(food);
return food;
}
}
class PandaKitchen implements Kitchen{
// Exact signature of the Kitchen
@Override
public void build(List<? super Food> plate) {
// the List IS a consumer of bamboos
plate.add(new Bamboo());
}
}
// Bamboo specialized restaurant
class OhPanda extends Restaurant {
public OhPanda() {
super(new PandaKitchen());
}
// Specialized signature of List<? extends Food>
@Override
List<Bamboo> getMeals() {
List<? super Food> bamboos = new ArrayList<>();
this.kitchen.build(bamboos);
// Obviously here, there is no information of having only Bamboos
return bamboos; // <==== FAIL
//return (List<Bamboo>) bamboos; // would not compile
}
}
最後の行では、私のOhPandaレストランがBamboosを生産していることを知っています。 List<? super Food>
をメモリに作成/コピーせずに変換するベストプラクティスは何ですか?
より完全な要旨はここに書かれている:https://gist.github.com/nicolas-zozol/8c66352cbbad0ab67474a776cf007427
私は別の解決策を追加しました。 –
これはうまくいきましたが、TとFがFoodを拡張しているところで、ちょっとした解決策を作りました:https://gist.github.com/nicolas-zozol/37748839e4bcfeaaf7cec914fb2442ce –
なぜthis.kitchen.build(bamboos);どのようにvoidビルド(リスト super F>プレート); '以前ビルドビルド(リスト<?スーパー食品>プレート);'これらのバンブーを受け入れなかったときにバンブーを受け入れることができますか? –