-
구조패턴 : Flyweight 패턴디자인패턴 2013. 2. 5. 09:30
분류 : 구조패턴(Structural Patterns)
정의 :
다른 유사한 객체와 가능한 많은 데이터를 공유함으로써 메모리 사용량을 최소화하는 객체를 flyweight라고 함.
용도 :
메모리 사용량을 줄여서 효율성을 높임.
소스
//Flyweight 객체 인터페이스 public interface CoffeeOrder { public void serveCoffee(CoffeeOrderContext context); } //ConcreteFlyweight를 생성하는 ConcreteFlyweight 객체 public class CoffeeFlavor implements CoffeeOrder { private final 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 final int tableNumber; public CoffeeOrderContext(int tableNumber) { this.tableNumber = tableNumber; } public int getTable() { return this.tableNumber; } } import java.util.HashMap; import java.util.Map; //FlyweightFactory 객체 public class CoffeeFlavorFactory { private Map
flavors = new HashMap (); 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); takeOrders("Frappe", 897); takeOrders("Cappuccino", 97); takeOrders("Cappuccino", 97); takeOrders("Frappe", 3); takeOrders("Xpresso", 3); takeOrders("Cappuccino", 3); takeOrders("Xpresso", 96); takeOrders("Frappe", 552); takeOrders("Cappuccino", 121); takeOrders("Xpresso", 121); for (int i = 0; i < ordersMade; ++i) { flavors[i].serveCoffee(tables[i]); } System.out.println(" "); System.out.println("total CoffeeFlavor objects made: " + flavorFactory.getTotalCoffeeFlavorsMade()); } } 참고자료
http://en.wikipedia.org/wiki/Flyweight_pattern#Immutability_.26_Equality
'디자인패턴' 카테고리의 다른 글
행위패턴 : Chain of Responsibility 패턴 (0) 2013.02.07 구조패턴 : Proxy 패턴 (0) 2013.02.06 구조패턴 : Facade 패턴 (0) 2013.01.29 구조패턴 : Decorator 패턴 (0) 2013.01.28 구조패턴 : Composite 패턴 (0) 2013.01.25 댓글