From the course: Java Design Patterns: Structural

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Solution: The Flyweight pattern

Solution: The Flyweight pattern - Java Tutorial

From the course: Java Design Patterns: Structural

Start my 1-month free trial

Solution: The Flyweight pattern

(upbeat music) - [Narrator] Now let's take a look at my solution to the exercise. As usual, yours might look a bit different than mine, and that's totally fine. So I've created a class called Animal Factory. This has a HashMap called Animals. Then there's a method called getAnimal. This checks, if the type of animal is already in the HashMap, and if it is, then it returns it. If it's not, then it creates a new one, adds it to the HashMap, and then returns that animal. Finally, in the Population Simulator class, I have a new field called Animal Factory, and inside there create Random Animal method. I'm setting the animal variable to animalFactory.getAnimal and passing in the random integer. So now if I run the app again, I can see in the console outputs that it's creating Lions and Tigers and they're showing different locations. But the object reference is the same for each Lion and each Tiger. So if for…

Contents