I have objects that will always carry 2 types of informations, and the rest could be anything else.
To achieve the DRY principle I created a parent object, that will hold those 2, and children objects that will hold everything else.
Builders will be responsible to create those objects. I have a parent builder which builds those 2 informations, and then create the parent object.
Children builders will extend the parent builder, and will use polymorphism to create the children objects.
How would be the best way(both object oriented way/design pattern) to achieve this?
So here's an example:
The parent object:
class Hamburger {
private Meat meat;
private Bread bread;
}
The child object:
class CheeseBurger extends Hamburger {
private Cheese cheese;
}
The parent builder:
abstract class HamburgerBuilder {
private Bread bread;
private Meat meat;
public HamburgerBuilder(Bread bread, Meat meat) {
this.bread = bread;
this.meat = meat;
}
public Hamburger build(Hamburger hamburger) {
Hamburger hamburger = new Hamburger();
hamburger.setBread(bread);
hamburger.setMeat(meat);
return hamburger;
}
}
The child builder:
class CheeseBurgerBuilder extends HamburgerBuilder {
private Cheese cheese;
public CheeseBurgerBuilder(Meat meat, Bread bread, Cheese cheese) {
super(bread, meat);
this.cheese = cheese;
}
public CheeseBurguer build() {
CheeseBurger cheeseburger = new CheeseBurger();
cheeseBurger = (CheeseBurger)super.build(cheeseBurger);
cheeseBurger.setCheese(cheese);
return cheeseBurguer;
}
}
So basically I can have multiple hamburger types, and all of them always have bread and meat.
The child builder(CheeseBurgerBuilder) will ask the parent builder to build the bread and meat, and after that he will build the cheese and put it in the CheeseBurger.
Is that the optimal way to create children objects and achieve good reuse of code?
The polymorphism I did in the children builders are correct? How to achieve a better polymorphism?
Or, should I:
- Use the decorator design pattern? But i don't think it fits well here since it's a structural pattern, and what im doing is creating;
- Use composition?
- Repeat the steps to create the basic hamburger in every children builder(although hurting the DRY principle)?
Aucun commentaire:
Enregistrer un commentaire