Created
March 30, 2013 02:11
-
-
Save java-interview/5274973 to your computer and use it in GitHub Desktop.
example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Flyweight object interface | |
public interface CoffeeOrder { | |
public void serveCoffee(CoffeeOrderContext context); | |
} | |
// ConcreteFlyweight object that creates ConcreteFlyweight | |
public class CoffeeFlavor implements CoffeeOrder { | |
private String flavor; | |
public CoffeeFlavor(String newFlavor) { | |
this.flavor = newFlavor; | |
} | |
public String getFlavor() { | |
return this.flavor; | |
} | |
public void serveCoffee(CoffeeOrderContext context) { | |
System.out.println("Serving Coffee flavor " + flavor + " to table number " + context.getTable()); | |
} | |
} | |
public class CoffeeOrderContext { | |
private int tableNumber; | |
public CoffeeOrderContext(int tableNumber) { | |
this.tableNumber = tableNumber; | |
} | |
public int getTable() { | |
return this.tableNumber; | |
} | |
} | |
import java.util.HashMap; | |
import java.util.Map; | |
//FlyweightFactory object | |
public class CoffeeFlavorFactory { | |
private Map<String, CoffeeFlavor> flavors = new HashMap<String, CoffeeFlavor>(); | |
public CoffeeFlavor getCoffeeFlavor(String flavorName) { | |
CoffeeFlavor flavor = flavors.get(flavorName); | |
if (flavor == null) { | |
flavor = new CoffeeFlavor(flavorName); | |
flavors.put(flavorName, flavor); | |
} | |
return flavor; | |
} | |
public int getTotalCoffeeFlavorsMade() { | |
return flavors.size(); | |
} | |
} | |
public class TestFlyweight { | |
/** The flavors ordered. */ | |
private static CoffeeFlavor[] flavors = new CoffeeFlavor[100]; | |
/** The tables for the orders. */ | |
private static CoffeeOrderContext[] tables = new CoffeeOrderContext[100]; | |
private static int ordersMade = 0; | |
private static CoffeeFlavorFactory flavorFactory; | |
public static void takeOrders(String flavorIn, int table) { | |
flavors[ordersMade] = flavorFactory.getCoffeeFlavor(flavorIn); | |
tables[ordersMade++] = new CoffeeOrderContext(table); | |
} | |
public static void main(String[] args) { | |
flavorFactory = new CoffeeFlavorFactory(); | |
takeOrders("Cappuccino", 2); | |
takeOrders("Cappuccino", 2); | |
takeOrders("Frappe", 1); | |
takeOrders("Frappe", 1); | |
takeOrders("Xpresso", 1); | |
for (int i = 0; i < ordersMade; ++i) { | |
flavors[i].serveCoffee(tables[i]); | |
} | |
System.out.println(" "); | |
System.out.println("total CoffeeFlavor objects made: " + flavorFactory.getTotalCoffeeFlavorsMade()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment