Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

nhibernate - Is it ever valid to convert an object from a base class to a subclass

In my application at the moment I have (as in so many other applications) an entity called Contact, which represents any person. At its most basic level this is used to represent business contacts. However it can also be used to represent employees of the company. and there are also a couple of special types of employee (let say there is one called Manager)

I am attempting to model this as an inheritance relationship which makes sense. Employees have names and addresses just like contacts, as well as a number of employment related attributes. Managers also have a number of manager specific attributes.

The difficulty comes when an employee gets promoted to a manager. Is it ok to convert the base class Employee to the inheriting class Manager? It feels wrong. I guess I would do it with a specialised constructor on Manager.

As an aside does NHibernate support this kind of behaviour? is it as simple as getting the employee, creating the manager from the employee, then saving the manager?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'd go with composition over inheritance in this case. If you stick with inheritance, you'll be changing classes with every promotion or demotion and every time you hire a contact or an employee leaves and becomes a regular Contact.

It's easier just to say Contacts have Roles. You can add a Manager Role to a contact to promote it and remove the Role to fire it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...