Add/edit form design pattern
Consider there is a list of companies and we can add a new company or edit an existing one. Adding and editing is performed using a form.
To render these forms 开发者_如何学PythonI need two classes: AddForm and EditForm. But they have a lot in common (fields, buttons and so on), so I generalize Form class:
class AddForm extends Form
class EditForm extends Form
Then I need to create a lot of forms: for companies, contacts, documents, users and so on. So I create a library with three base classes:
abstract class BaseForm
abstract class BaseAddForm extends BaseForm
abstract class BaseEditForm extends BaseForm
Now I am trying to create an implementation for companies:
class CompanyForm extends BaseForm
class CompanyAddForm extends BaseAddForm, CompanyForm
OOPS! Multiple inheritance isn't allowed.
What should I do?
UPDATE: I heard that need for multiple inheritance means bad design. Could anyone show me how this design could be reworked?
Sounds like composition is what you want to use. A Form has a list of FormPanels.
First of all I would combine these functions into a single form as has been suggested by Kaj. This is a function where a list of Company objects is administered. That is a reasonable degree of granularity for a typical user - administer, i.e either add or edit a Company from a single form.
Second in terms of the multiple inheritance issue, you say you need two forms, Add, Edit. OK, I disagree but let's go with that anyway.
You say "But they have a lot in common (fields, buttons and so on), so I generalize Form class". I question the basis for generalization here. Lots of fields and buttons in common? What fields and buttons do, example, a DocumentEdit and CompanyEdit form have in common? The Edit button, anything else?
Now, CompanyAdd and CompanyEdit yes they are going to have a lot in common. That would suggest that the add and edit forms extend some parent specific form instead of these abstract add/edit bases. Just get rid of BaseFormAdd and BaseFormEdit. How much common functionality are you really going to have between example, a Document form and a Company form? Seems like a common base Add or Edit form adds very little of use. You can do without that inheritance line. In terms of multiple inheritance, I only encounter a situation in which it would be useful, to the point I feel like I really need it only very rarely.
精彩评论