Java Design Patterns Flyweight Patterns

Introduction

Flyweight Patterns can support large numbers of fine-grained objects efficiently.

Flyweight Patterns try to minimize memory usage by sharing data as much as possible.

Use case

  • Manage characters of a computer game

Example

import java.util.HashMap;
import java.util.Map;

interface Flight {
   void Print();//  w w  w  .  j  a va2 s  .  c  om
}

class SmallFlight implements Flight {
   @Override
   public void Print() {
      System.out.println("Small Flight");
   }
}

class LargeFlight implements Flight {
   @Override
   public void Print() {
      System.out.println("Large Flight");
   }
}

class FlightFactory {
   Map<String, Flight> flightMap = new HashMap<String, Flight>();

   public int TotalObjectsCreated() {
      return flightMap.size();
   }

   public Flight GetFlightFromFactory(String FlightCategory) throws Exception {
      Flight robotCategory = null;
      if (flightMap.containsKey(FlightCategory)) {
         robotCategory = flightMap.get(FlightCategory);
      } else {
         switch (FlightCategory) {
         case "small":
            robotCategory = new SmallFlight();
            flightMap.put("small", robotCategory);
            break;
         case "large":
            robotCategory = new LargeFlight();
            flightMap.put("large", robotCategory);
            break;
         default:
            throw new Exception("wrong type");
         }
      }
      return robotCategory;
   }
}
public class Main {
   public static void main(String[] args) throws Exception {
      FlightFactory myfactory = new FlightFactory();

      Flight shape = myfactory.GetFlightFromFactory("small");
      shape.Print();

      for (int i = 0; i < 2; i++) {
         shape = myfactory.GetFlightFromFactory("small");
         shape.Print();
      }
      int NumOfDistinctFlights = myfactory.TotalObjectsCreated();
      System.out.println("Distinct Flight objects:" + NumOfDistinctFlights);
      for (int i = 0; i < 5; i++) {
         shape = myfactory.GetFlightFromFactory("large");
         shape.Print();
      }
      NumOfDistinctFlights = myfactory.TotalObjectsCreated();
      System.out.println("Distinct Flight objects: " + NumOfDistinctFlights);
   }
}



PreviousNext

Related