Mission impossible? (babysloth, wangwenyou, jimjxr, abcabcabc please come in)

ajoo ajoo 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
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?
...全文

相关推荐

评论 6
收藏 已收藏
分享
返回顶部
ajoo
Java SE 62,621 成员 307,251 内容