Si, I have this kind of hierarchy in the class design:
What i wanted to achieve is the most versatile class design that will be flexible enough to cover all the cases.
As you can see in the image, we have cages which are of some material. Now, depending on material type, we can have further categorization inside the cage based on the color (so, in case of plastic cage, we will have 2 compartments where one is red and other is blue) holding animals.
In case of more specific cages (e.g. PLASTIC one), I should be able to call getBrightestColor(), which is not present for METAL cage. Case of WOOD-en cage is just more complex PLASTIC one.
This is some code that I have so far, but I don't think neither is OK (added possible problems in comment in code):
Cage cg = new Cage(new Specifier(Material.METAL));
cg.addAnimal(new Elephant());
cg.addAnimal(new Dog());
cg.addAnimal(new Cat());
cg.emptyCage();
CageWithSpecifier cg2 = new CageWithSpecifier(new Specifier(Material.PLASTIC)); //need to have different class than Cage, and they are more less same??
cg2.addAnimal(new Specifier(Color.RED), new Dog());
cg2.addAnimal(new Specifier(Color.RED), new Elephant());
cg2.addAnimal(new Specifier(Color.BLUE), new Elephant());
cg2.addAnimal(new Specifier(Color.BLUE), new Cat());
String bc1 = cg2.getBrightestColor();
cg2.emptyCage();
CageWithSpecifier cg3 = new CageWithSpecifier(new Specifier(Material.WOOD));
cg3.addAnimal(new Specifier(Wood.OAK, Color.RED), new Dog());
cg3.addAnimal(new Specifier(Wood.OAK, Color.BLACK), new Elephant());
cg3.addAnimal(new Specifier(Wood.MAPLE, Color.RED), new Dog());
//cg3.getBySpecifier --> ideally should know if it returns leaf or node in hierarchy (without casting?); here we need to cast and whatnot
String bc2 = cg3.getBySpecifier(new Specifier(Wood.OAK)).getBrightestColor();
And this one using composite:
//using Composite pattern ?
Cage cg3 = new Cage(new Specifier(Material.WOOD));
Cage cg3s1 = new Cage(new Specifier(Wood.OAK)); //cg3s1 is not leaf, but has addAnimal()
Cage cg3s1s1 = new Cage(new Specifier(Color.RED)); //cg3s1s1 is leaf, but will have also addCage()
cg3s1s1.addAnimal(new Dog());
cg3s1.addCage(cg3s1s1);
cg3.addCage(cg3s1);
I guess it should be some kind of Composite pattern? Anyone has better suggestions?

Aucun commentaire:
Enregistrer un commentaire