设计模式:享元模式

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

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值