gpt4 book ai didi

java - PECS:如何将消费者转变为生产者?

转载 作者:行者123 更新时间:2023-11-30 02:27:42 26 4
gpt4 key购买 nike

我有一家提供餐食的餐厅。厨房里的盘子是消费者的。

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 餐厅只生产竹子。转换我的 List<? super Food> 的最佳做法是什么?无需在内存中创建/复制 ArrayList ?

更完整的要点写在这里:https://gist.github.com/nicolas-zozol/8c66352cbbad0ab67474a776cf007427

最佳答案

或者,也许您可​​以编写餐厅和厨房的打字版本?

package kitchen;

import java.util.ArrayList;
import java.util.List;

class Food{}
class Bamboo extends Food {}

interface Kitchen<F> {
void build(List<F> dessert);
}

abstract class Restaurant<T> {
protected Kitchen kitchen;

Restaurant(Kitchen kitchen) {
this.kitchen = kitchen;
}

List<T> getMeals() {
List<T> food = new ArrayList<>();
kitchen.build(food);
return food;
}
}

class PandaKitchen implements Kitchen<Bamboo>{

@Override
public void build(List<Bamboo> dessert)
{
dessert.add(new Bamboo());
}
}

/** Bamboo specialized restaurant*/
class OhPanda extends Restaurant<Bamboo> {

OhPanda() {
super(new PandaKitchen());
}

@Override
List<Bamboo> getMeals() {
List<Bamboo> bamboos = new ArrayList<>();
kitchen.build(bamboos);
return bamboos;
}
}

关于java - PECS:如何将消费者转变为生产者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45212443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com