我需要从现有的Fruit对象构造类,例如Apple或Strawberry。
这是我的水果课:
public class Fruit {
int somevariable;
Thread somethread;
public Fruit(int somevariable) {
this.somevariable = somevariable;
this.somethread = new Thread() {
public void run() { /* Something here */ }
}
this.somethread.start();
}
public Fruit(Fruit fruit) {
this.somevariable = fruit.somevariable;
this.somethread = fruit.somethread;
}
}
这是我的苹果和草莓课:
public class Apple extends Fruit {
public Apple(Fruit fruit) {
super(fruit);
}
}
public class Strawberry extends Fruit {
public Strawberry(Fruit fruit) {
super(fruit);
}
}
我有这样的HashMap:
HashMap<Integer, Fruit> fruits = new HashMap<>();
首先,我要添加以下水果:
(我所知道的是,目前这是水果。我不能立即添加苹果或草莓。)
fruits.put(17, new Fruit(4));
fruits.put(24, new Fruit(8));
fruits.put(95, new Fruit(12));
当我发现它是哪种水果时,我需要用苹果或草莓(与超级对象具有相同的水果对象)替换该水果对象。当然不用停止一些线程。
这就是我解决的方法:
fruits.replace(17, new Strawberry(fruits.get(17)));
fruits.replace(24, new Apple(fruits.get(24)));
fruits.replace(95, new Strawberry(fruits.get(95)));
我的问题是:
可以简化吗?我的解决方案正确吗?
还有一个问题,如果我的草莓中有经常从其他线程调用的函数,那么如何确保在哈希映射值替换期间没有问题?
非常感谢您的帮助 :)
最佳答案
偏好组合而非继承。子类化具体的类(尽管Object
除外,尽管目前具体化有点被“弃用”)通常并不好。Fruit
应该有一个FruitType
(或更好的名称)。根据需要委托。
还要注意,在原始代码中,将在原始Runnable
实例的上下文中创建Thread
(编辑:run
,且没有覆盖的Fruit
)。同样,线程最初会看到不能保证完全初始化的Fruit
。