Mission impossible? (babysloth, wangwenyou, jimjxr, abcabcabc please come in)
ajoo 2002-05-12 04:28:05 Now we have Array interface, Sequence interface, 4 decorator classes RotateSequence, ReverseSequence, SliceSequence, ConcatSequence, 1 bridge class Array2Sequence
(people who don't know the background of this question, please refer
http://www.csdn.net/expert/topic/690/690270.xml?temp=.7524835 and
http://www.csdn.net/expert/topic/700/700322.xml?temp=.7635614)
we use state pattern, responsibility chain, bridge pattern, decorator pattern in those classes.
And that pretty much solves our nested decorator problem.
Wonderful world, isn't it?
In my practice, I also have read-only array, write-only array, typed array etc.
public interface ArrayR
{
public int getLength();
public Object get(int i);
}
public interface ArrayW
{
public int getLength();
public void set(int i, Object val);
}
public interface Array extends ArrayR, ArrayW
{
public int getLength();
public Object get(int i);
public void set(int i, Object val);
}
public interface TypedArray extends Array
{
public Class getComponentType();
}
So that, in a method like ArrayUtil.binarySearch(ArrayR, Object, Comparator), I can search any ArrayR. (it does not have to be writable).
In a method like ArrayUtil.copyArray(ArrayR, ArrayW), the source array only needs to be readable, the dest array only needs to be writable.
OK. since we have slice, rotate, reverse, concat operations on Array, there's no reason we don't have them for ArrayR, ArrayW, TypedArray.
If I implement RotateSequenceR, ReverseSequenceR, RotateSequenceW etc, the impl will be pretty much the same as what we do for Array and Sequence. I can do copy&paste+minor changes, and I'll be all set.
That means, I'll need to write (or copy) similar code for 3*5=15 times. And if I also introduce TypedArrayR, TypedArrayW, the number will become 25.
Hooray! We are done!
But, wait a minute! Is that so great though? COPY&PASTE! Bad smell, isn't it?
How can I avoid copy&paste and reuse code as much as possible?
I don't have a solution in Java. Could not figure out a neat way even with GJ's parametric polymorphism. But C++'s template approach might work for this case. (not sure though)
Guys, your expertise is called for!
Babysloth: your ideas?