首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

设计模式:享元方式

2014-01-05 
设计模式:享元模式享元模式用来最大限度的减少内存使用。它所做的就是尽可能多的同其他类似对象共享数据。通

设计模式:享元模式

享元模式用来最大限度的减少内存使用。它所做的就是尽可能多的同其他类似对象共享数据。通常与工厂模式一起使用。

1、类图


设计模式:享元方式
?2、JAVA代码实例

?

?

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

?

?

热点排行