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.
Implement the Fyweight pattern - Java Tutorial
From the course: Java Design Patterns: Structural
Implement the Fyweight pattern
- [Instructor] The first thing I'm going to do to implement the flyweight pattern is to implement a class to represent that flyweight object. So I'm going to create a new class by right clicking on the Java package and going to New, Java Class. And I'll call this vehicle factory. In this class, I want to check if a vehicle object of the specified type already exists. And if it does, then reference that. If it doesn't, then I'll create a new one. So first, I'm going to create a field of type hashmap, which I'll call vehicles. And this is to store the two different types of vehicle. In my traffic simulator class, I'm using a random number to decide which kind of vehicle to create. If it's a zero, then I create a car, and if it's a one, then I create a truck. So in my hashmap, the key is going to be an integer, and the value is going to be a vehicle. Next, I need a method to check if the type of vehicle already exists, and…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.