In [this post], I’m struggling to implement a State Pattern as @jonp suggests. I don’t quite get how to use what’s he’s posted but it leads to the thought that maybe I’m trying to fit a square peg into a round hole. So my question:
If I have a visitor to my site that can play multiple roles i.e. a User could be a Vendor, an Employer, an Advertiser, OR all of the above, should I be using inheritance? I’ve declared:
class Vendor : User {}
class Advertiser : User {}
et cetera, but when a user is both a vendor and an employer then instances of different classes really point to the same underlying object… I’m not sure this can work. How do I model it?
* update *
thanks everyone (you all get a point (it’s all I can give)). I’ve been pulling my hair out over deep-copies with EF, downcasting and the state pattern for the last several days. The role approach makes much more sense.
This sounds like a situation to which the attribute pattern (or so I call it) would be very appropriate. It’s a much more loosely-coupled approach than simple inheritance that can be used to specify multiple “behaviours” or in your case kinds of
User. It’s really nothing more complicated than an object having tags of another kind of object.The easiest way to implement it would be to have a concrete
Userclass, with a read-only propertyIList<UserRole>(internally this can be aList<T>field perhaps). YourUserRoleclass would then be abstract, andVendorRole/AdvertiserRole/etc. would derive from it, allowing you to tag on an arbitrary number of different roles (even ones of the same type) onto a given user. These roles can in addition define their own custom behaviours, utility methods, etc.In addition, you could define a
GetRole<TRole>method on yourUserclass to facilitate access to roles of a specific type (assuming eachUseronly has a singleRoleof a specific subtype).Side note: you may also consider the decorator patern, which is closely related to the above mentioned pattern — though personally I feel it is overkill here, and really adds nothing in terms of flexibility or power. It often just obscures what you’re trying to do; though feel free to investigate anyway.