设计模式学习笔记八:享元模式

享元模式,又叫蝇量模式:适用于是小类的复用,多与工厂模式配合使用。没看设计模式的人,在coding的时候应该会不知不觉中写过这种结构的代码,只不过不知道名字叫什么而已。

享受模式详细定义:传送门


上代码:

 

package com.liushijie.flyweight;

import java.util.HashMap;

public class Run {
	public static void main(String[] args) {
		// 调用
		FruitFactory factory = new FruitFactory();
		factory.doEat("apple");
		factory.doEat("banana");
		factory.doEat("orange");
	}
}

class FruitFactory {
	private HashMap<String, Fruit> fruits = new HashMap<String, Fruit>();

	public FruitFactory() {
		// 初始化蝇量元素
		fruits.put("apple", new Apple());
		fruits.put("banana", new Banana());
		fruits.put("orange", new Orange());
	}

	/**
	 * 吃掉
	 * 
	 * @param type
	 */
	public void doEat(String type) {
		Fruit fruit = fruits.get(type);
		fruit.eat();
	}
}

/**
 * 水果接口
 * 
 * @author array7
 * 
 */
interface Fruit {
	/**
	 * 吃接口
	 */
	public void eat();
}

/**
 * 苹果
 * 
 * @author array7
 * 
 */
class Apple implements Fruit {

	@Override
	public void eat() {
		System.out.println("eat a apple...");
	}

}

/**
 * 橘子
 * 
 * @author array7
 * 
 */
class Orange implements Fruit {

	@Override
	public void eat() {
		System.out.println("eat a orange...");
	}

}

/**
 * 香蕉
 * 
 * @author array7
 * 
 */
class Banana implements Fruit {

	@Override
	public void eat() {
		System.out.println("eat a banana...");
	}

}
posted @ 2015-06-26 19:21  土豆条  阅读(153)  评论(0编辑  收藏  举报