Java Design Patterns Flyweight Patterns with modified objects

Description

Java Design Patterns Flyweight Patterns with modified objects

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

interface Printable {
   void Print();//from w w w  .j  a  va 2s  .  c o  m
}

class Card implements Printable {
   private String type;
   public String colorOfCard;

   public Card(String type) {
      this.type = type;
   }

   public void setColor(String colorOfCard) {
      this.colorOfCard = colorOfCard;
   }

   @Override
   public void Print() {
      System.out.println(type + " with " + colorOfCard + " color");
   }
}

class CardFactory {
   Map<String, Printable> shapes = new HashMap<String, Printable>();

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

   public Printable GetCardFromFactory(String type) throws Exception {
      Printable CardCategory = null;
      if (shapes.containsKey(type)) {
         CardCategory = shapes.get(type);
      } else {
         switch (type) {
         case "King":
            CardCategory = new Card("King");
            shapes.put("King", CardCategory);
            break;
         case "Queen":
            CardCategory = new Card("Queen");
            shapes.put("Queen", CardCategory);
            break;
         default:
            throw new Exception("wrong type");
         }
      }
      return CardCategory;
   }
}

public class Main {
   public static void main(String[] args) throws Exception {
      CardFactory myfactory = new CardFactory();
      Card shape;
 
      for (int i = 0; i < 3; i++) {
         shape = (Card) myfactory.GetCardFromFactory("King");
         shape.setColor(getRandomColor());
         shape.Print();
      }
 
      for (int i = 0; i < 3; i++) {
         shape = (Card) myfactory.GetCardFromFactory("Queen");
         shape.setColor(getRandomColor());
         shape.Print();
      }
      System.out.println("Distinct Card objects created: " + myfactory.TotalObjectsCreated());
   }

   static String getRandomColor() {
      Random r = new Random();
      int random = r.nextInt(20);
      if (random % 2 == 0) {
         return "red";
      } else {
         return "green";
      }
   }
}



PreviousNext

Related