import java.util.EnumMap;
import java.util.Map;

/**
 * {@link <a href=
 * "https://[Log in to view URL]"
 * target= "_blank"></a>}
 * 
 * @author itammb ( Italia Massimiliano Buscati )
 * @version JDK 1.15
 *
 */
class Main {
    public static enum PotionType {                
		HEALING, HOLY_WATER, INVISIBILITY
	}
	
	public interface Potion {
		  void request(int quantity);
	}
	
	public static class FlyweightPotion implements Potion {
		
		private PotionType pointType;   // campo intrinseco (immutabile)
		
		public FlyweightPotion(PotionType pointType) {
			this.pointType = pointType;
		}

		public void request(int quantity) {
			System.out.println(this + "quantity -> " +  quantity);
		}

		@Override
		public String toString() {
			return "FlyweightPotion [pointType=" + pointType + ", getClass()=" + getClass() + ", hashCode()="
					+ hashCode() + "]";
		}
	}

	public static class PotionFactory {

		private final Map<PotionType, Potion> potions; // cache

		public PotionFactory() {
			potions = new EnumMap<>(PotionType.class);
		}

		public Potion getPotion(PotionType type) {
			var potion = potions.get(type);
			if (potion == null) {
				switch (type) {
				case HEALING -> potion = new FlyweightPotion(PotionType.HEALING);
				case HOLY_WATER -> potion = new FlyweightPotion(PotionType.HOLY_WATER);
				case INVISIBILITY -> potion = new FlyweightPotion(PotionType.INVISIBILITY);
				default -> {
				}
				}
				potions.put(type, potion);
			}
			return potion;
		}
	}
	
	public static class ContextShop {
		private Potion potion;
		private PotionType pointType;
		private int quantity;
		
		public ContextShop(PotionFactory potionFactory, PotionType pointType, int quantity) {
			this.potion = potionFactory.getPotion(pointType);
			this.pointType = pointType;
			this.quantity = quantity;
		}
		
		public void request() {
			potion.request(quantity);
		}	
	}

	public static void main(String args[]) {
		// Unit test - uso del design pattern: flyweight
		PotionFactory potionFactory = new PotionFactory();
		
		ContextShop shop = new ContextShop(potionFactory, PotionType.INVISIBILITY, 1);
		shop.request();
		
		shop = new ContextShop(potionFactory, PotionType.HOLY_WATER,2);
		shop.request();
		
		shop = new ContextShop(potionFactory, PotionType.HEALING, 3);
		shop.request();

		shop = new ContextShop(potionFactory, PotionType.INVISIBILITY, 2);
		shop.request();
	}
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: