使用合成不能扩展(是的,我的意思是扩展,就像在Java中对extends关键字的引用一样,是的,这是继承)。组成部分是更好的,因为它完全屏蔽了您的实现,使您可以在不影响类用户的情况下更改实现。
我建议您尝试类似的操作(我直接在此窗口中输入内容,因此买方请注意语法错误):
public LimitedSizeQueue implements Queue
{
private int maxSize;
private LinkedList storageArea;
public LimitedSizeQueue(final int maxSize)
{
this.maxSize = maxSize;
storageArea = new LinkedList();
}
public boolean offer(ElementType element)
{
if (storageArea.size() < maxSize)
{
storageArea.addFirst(element);
}
else
{
... remove last element;
storageArea.addFirst(element);
}
}
... the rest of this class
更好的选择(基于Asaf的回答)可能是用通用类包装Apache Collections CircularFifoBuffer。例如:
public LimitedSizeQueue<ElementType> implements Queue<ElementType>
{
private int maxSize;
private CircularFifoBuffer storageArea;
public LimitedSizeQueue(final int maxSize)
{
if (maxSize > 0)
{
this.maxSize = maxSize;
storateArea = new CircularFifoBuffer(maxSize);
}
else
{
throw new IllegalArgumentException("blah blah blah");
}
}
... implement the Queue interface using the CircularFifoBuffer class
}