package com.javapatterns.flyweight.coffeeshop; public class Flavor extends Order { private String flavor; public Flavor(String flavor) { this.flavor = flavor; } public String getFlavor() { return this.flavor; } public void serve(Table table) { System.out.println("Serving table " + table.getNumber() + " with flavor " + flavor ); } }
package com.javapatterns.flyweight.coffeeshop; public class Table { private int number; public Table(int number) { this.number = number; } public void setNumber(int number) { this.number = number; } public int getNumber() { return number; } }
package com.javapatterns.flyweight.coffeeshop; public class FlavorFactory { /** * @label Flyweight * @link aggregation */ private Order[] flavors = new Flavor[10]; private int ordersMade = 0; private int totalFlavors = 0 ; public Order getOrder(String flavorToGet) { if (ordersMade > 0) { for (int i = 0; i < ordersMade; i++) { if (flavorToGet.equals((flavors[i]).getFlavor())) { return flavors[i]; } } } flavors[ordersMade] = new Flavor(flavorToGet); totalFlavors++; return flavors[ordersMade++]; } public int getTotalFlavorsMade() { return totalFlavors; } }
package com.javapatterns.flyweight.coffeeshop; public class Client { //the flavors ordered /** * @label Creates */ private static Order[] flavors = new Flavor[100]; private static int ordersMade = 0; private static FlavorFactory flavorFactory; /** @link dependency */ /*#Table lnkTable;*/ private static void takeOrders(String aFlavor) { flavors[ordersMade++] = flavorFactory.getOrder(aFlavor); } public static void main(String[] args) { flavorFactory = new FlavorFactory(); takeOrders("Black Coffee"); takeOrders("Capucino"); takeOrders("Espresso"); takeOrders("Espresso"); takeOrders("Capucino"); takeOrders("Capucino"); takeOrders("Black Coffee"); takeOrders("Espresso"); takeOrders("Capucino"); takeOrders("Black Coffee"); takeOrders("Espresso"); for (int i = 0; i < ordersMade; i++) { flavors[i].serve(new Table(i)); } System.out.println(" Total teaFlavor objects made: " + flavorFactory.getTotalFlavorsMade()); } }
《java与模式》中的咖啡屋代码,拿来理解“享元模式”非常合适!