Can you clone an anonymous object? (Java / OOP)

2019-07-18 22:22发布

I'm creating a library of very common, very simple shapes. Sphere would be a member, as well as torus, and so on. Torus has two radius fields, whereas sphere has one; that modified behavior is something we can provide by changing the implementation of functions to include both radii, and of course, adding the extra radius field. Torus is common enough that inclusion of that behavior in the permanent library is beneficial.

On the other hand, "WigglyTorus", a torus whose radii oscillate, would not be a member of the permanent library. Instead, an anonymous class is more useful; it can store the desired behavior just as well, but externally, it is treated just like an ordinary torus.

Therein lies the problem. If I want to clone a torus, my new torus can behave exactly the same. If I want to clone a WigglyTorus, the reproduced behaviors will mimic the behaviors of torus, and I don't really have a clone at all. But two uses of WigglyTorus does not justify the addition of WigglyTorus as a permanent class.

I've thought about workarounds, but none of them seem elegant. I feel like I'm missing something significant about either Java or OOP.

0条回答
登录 后发表回答