jeudi 22 juin 2017

Factory Pattern or Extended Method?

I am studying Design Patters and I have a situation where I am not sure what would be a better practice:

I have a class "Category" which has several fields: name, 2 kinds of urls, list of related objects. There is a method 'toHtml()' which basically generates some HTML from instances of that class.

There are 4 different types of 'Categories' which have exactly the same fields but 'toHtml()' method should give different result for each one.

I am not sure if I should pass a parameter "type" and series of ifs/switch statement to generate different html or should I make a Category class abstract and create several sub-classes that override the toHtml() method and then use CategoryFactory class to generate them? In both cases I need to pass 'type' parameter.

I tried to think about 'Close for modification, open for extension' OOP rule. But in this case if I want to add 'fifth' category type, that generates different html - for first solution I need to modify only toHtml method (adding one more if), going for second solution I need to create additional sub-class AND modify CategoryFactory class.

What would be better practice? Is there any extra rule I should follow when I have similar kind of dilemma?

Aucun commentaire:

Enregistrer un commentaire