I'm trying to implement a builder pattern in javascript. I have a class Director
that can build different animals.
The animal is created in a class called AnimalBuilder
. The idea is to get a collection of methods to instantiate many different keys in an object which will be very different based on the animal.
It almost works. The constructor of the AnimalBuilder class is properly updated, but I can't access this simple object so far. All I receive is a constructor object.
class AnimalBuilder {
constructor(name) {
this.name = name;
}
setSpecy(specy) {
this.specy = specy;
return this;
}
setIsComestible(isComestible) {
this.isComestible = isComestible;
return this;
}
create() {
return this;
}
}
class Director {
buildCat(builder) {
return builder
.setSpecy("cat")
.setIsComestible(false)
.create();
}
buildCow(builder) {
return builder
.setSpecy("cow")
.setIsComestible(true)
.create();
}
}
const director = new Director();
const animalBuilder = new AnimalBuilder("Jenny");
const cow = director.buildCow(animalBuilder);
console.log(cow);
// output: AnimalBuilder {
// name: "Jenny",
// specy: "cow",
// isComestible: true
// }
How to only receive:
{
name: "Jenny",
specy: "cow",
isComestible: true
}
Thanks!
Aucun commentaire:
Enregistrer un commentaire