Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- The Flyweight Pattern is a structural design pattern that is used to minimize memory usage or computational expenses by sharing as much as possible with related objects. It is particularly useful when there are a large number of similar objects in an application.
- Here's a simple example of the Flyweight Pattern in Java, where we'll create a simple Flyweight factory for creating and managing shared "Character" objects:
- java
- Copy code
- import java.util.HashMap;
- import java.util.Map;
- // Flyweight interface
- interface Character {
- void display();
- }
- // Concrete Flyweight
- class ConcreteCharacter implements Character {
- private char symbol;
- ConcreteCharacter(char symbol) {
- this.symbol = symbol;
- }
- @Override
- public void display() {
- System.out.print(symbol);
- }
- }
- // Flyweight Factory
- class CharacterFactory {
- private Map<Character, Character> characters = new HashMap<>();
- Character getCharacter(char symbol) {
- characters.putIfAbsent(symbol, new ConcreteCharacter(symbol));
- return characters.get(symbol);
- }
- }
- // Client Code
- public class Client {
- public static void main(String[] args) {
- CharacterFactory characterFactory = new CharacterFactory();
- // Create and display characters
- Character charA = characterFactory.getCharacter('A');
- charA.display();
- Character charB = characterFactory.getCharacter('B');
- charB.display();
- Character charA2 = characterFactory.getCharacter('A'); // Reusing the 'A' character
- charA2.display();
- // Output: AB
- }
- }
- In this example:
- Character is the Flyweight interface.
- ConcreteCharacter is the Concrete Flyweight that implements the Character interface.
- CharacterFactory is the Flyweight Factory that manages and creates flyweight objects. It ensures that only one instance of a character with a specific symbol is created and shared.
- The client code creates characters through the CharacterFactory, and if the character with a specific symbol has already been created, it reuses the existing instance. This way, the memory usage is minimized when dealing with a large number of similar characters.
Advertisement
Add Comment
Please, Sign In to add comment