享元模式用来最大限度的减少内存使用。它所做的就是尽可能多的同其他类似对象共享数据。通常与工厂模式一起使用。
1、类图
2、JAVA代码实例
// 享元对象接口
interface ICoffee {
public void serveCoffee(CoffeeContext context);
}
// 具体的享元对象
class Coffee implements ICoffee {
private final String flavor;
public Coffee(String newFlavor) {
this.flavor = newFlavor;
System.out.println("Coffee is created! - " + flavor);
}
public String getFlavor() {
return this.flavor;
}
public void serveCoffee(CoffeeContext context) {
System.out.println("Serving " + flavor + " to table "
+ context.getTable());
}
}
// 上下文,存着桌子号码
class CoffeeContext {
private final int tableNumber;
public CoffeeContext(int tableNumber) {
this.tableNumber = tableNumber;
}
public int getTable() {
return this.tableNumber;
}
}
咖啡工厂:需求某种咖啡时,只创建此种咖啡一次。
// 享元工厂
class CoffeeFactory {
private HashMap<String, Coffee> flavors = new HashMap<String, Coffee>();
public Coffee getCoffeeFlavor(String flavorName) {
Coffee flavor = flavors.get(flavorName);
if (flavor == null) {
flavor = new Coffee(flavorName);
flavors.put(flavorName, flavor);
}
return flavor;
}
public int getTotalCoffeeFlavorsMade() {
return flavors.size();
}
}
public class TestFlyweight {
// 咖啡数组
private static Coffee[] coffees = new Coffee[20];
// 桌子数组
private static CoffeeContext[] tables = new CoffeeContext[20];
private static int ordersCount = 0;
private static CoffeeFactory coffeeFactory;
public static void takeOrder(String flavorIn, int table) {
coffees[ordersCount] = coffeeFactory.getCoffeeFlavor(flavorIn);
tables[ordersCount] = new CoffeeContext(table);
ordersCount++;
}
public static void main(String[] args) {
coffeeFactory = new CoffeeFactory();
takeOrder("Cappuccino", 2);
takeOrder("Cappuccino", 2);
takeOrder("Regular Coffee", 1);
takeOrder("Regular Coffee", 2);
takeOrder("Regular Coffee", 3);
takeOrder("Regular Coffee", 4);
takeOrder("Cappuccino", 4);
takeOrder("Cappuccino", 5);
takeOrder("Regular Coffee", 3);
takeOrder("Cappuccino", 3);
for (int i = 0; i < ordersCount; ++i) {
coffees[i].serveCoffee(tables[i]);
}
System.out.println("\nTotal Coffee objects made: "
+ coffeeFactory.getTotalCoffeeFlavorsMade());
}
}
看下输出打印:为10个桌子的顾客提供了咖啡,但是只创建了两次咖啡。
输出
Coffee is created! - Cappuccino
Coffee is created! - Regular Coffee
Serving Cappuccino to table 2
Serving Cappuccino to table 2
Serving Regular Coffee to table 1
Serving Regular Coffee to table 2
Serving Regular Coffee to table 3
Serving Regular Coffee to table 4
Serving Cappuccino to table 4
Serving Cappuccino to table 5
Serving Regular Coffee to table 3
Serving Cappuccino to table 3
Total Coffee objects made: 2
Coffee is created! - Regular Coffee
Serving Cappuccino to table 2
Serving Cappuccino to table 2
Serving Regular Coffee to table 1
Serving Regular Coffee to table 2
Serving Regular Coffee to table 3
Serving Regular Coffee to table 4
Serving Cappuccino to table 4
Serving Cappuccino to table 5
Serving Regular Coffee to table 3
Serving Cappuccino to table 3
Total Coffee objects made: 2