Note that there are some explanatory texts on larger screens.

plurals
  1. POChanging the type of an entity at some point of its life
    text
    copied!<p>I have the following hierarchy: Party is a base class, extended by Person and Corporation. I need to change the object class of an entity at some point of its life, and I don't know what's the best way to do this.</p> <p>I'm modeling the financial world, so I have that a Party can own shares of a Corporation, while only Corporation can have shareholders. Something like this:</p> <pre><code>class Party { public Set getShares(); } class Corporation extends Party { public Set getShareholders(); public void setShareholders(Party ss); } class Person extends Party { ... (some method still unknown) } </code></pre> <p>I build the objects reading data from a source, and it can happen that at first I know only the name of a party, but I don't know whether it is a Person or a Corporation. But I need to create an object, so I create a generic Party. After that, it may happen that I come to know more infos, such that my Party was a Corporation. So, I need to change the class that represents that entity from Party to Corporation. Until now, my solution was to build a new object, copying the old data into it. But I'm not satisfied with it, and I'm wondering what's the best way, pattern or whatever else, to implement what I'd like to achieve.</p> <p>I thought to the <a href="http://www.javaworld.com/jw-08-1997/jw-08-stated.html" rel="nofollow">State Pattern</a>, but I think it is best suited for other situations.</p> <p>In general, I don't want <em>really</em> to change the class of the objects. What I want is to have some mechanism to make client classes to obey to the contracts of the different types. I.e., I don't want a class to be able to call setShareholders on a Person, and it's not important how I can achieve this, I mean that maybe the fact that an entity is a Person can be represented on other ways than using a class Person.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload