Guest User

Fly Weight Pattern

a guest
Dec 11th, 2023
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. 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.
  2.  
  3. 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:
  4.  
  5. java
  6. Copy code
  7. import java.util.HashMap;
  8. import java.util.Map;
  9.  
  10. // Flyweight interface
  11. interface Character {
  12. void display();
  13. }
  14.  
  15. // Concrete Flyweight
  16. class ConcreteCharacter implements Character {
  17. private char symbol;
  18.  
  19. ConcreteCharacter(char symbol) {
  20. this.symbol = symbol;
  21. }
  22.  
  23. @Override
  24. public void display() {
  25. System.out.print(symbol);
  26. }
  27. }
  28.  
  29. // Flyweight Factory
  30. class CharacterFactory {
  31. private Map<Character, Character> characters = new HashMap<>();
  32.  
  33. Character getCharacter(char symbol) {
  34. characters.putIfAbsent(symbol, new ConcreteCharacter(symbol));
  35. return characters.get(symbol);
  36. }
  37. }
  38.  
  39. // Client Code
  40. public class Client {
  41. public static void main(String[] args) {
  42. CharacterFactory characterFactory = new CharacterFactory();
  43.  
  44. // Create and display characters
  45. Character charA = characterFactory.getCharacter('A');
  46. charA.display();
  47.  
  48. Character charB = characterFactory.getCharacter('B');
  49. charB.display();
  50.  
  51. Character charA2 = characterFactory.getCharacter('A'); // Reusing the 'A' character
  52. charA2.display();
  53.  
  54. // Output: AB
  55. }
  56. }
  57. In this example:
  58.  
  59. Character is the Flyweight interface.
  60. ConcreteCharacter is the Concrete Flyweight that implements the Character interface.
  61. 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.
  62. 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