享元模式,又叫蝇量模式(有点恶心):适用于是小类的复用,多与工厂模式配合使用。没看设计模式的人,在coding的时候应该会不知不觉中写过这种结构的代码,只不过不知道名字叫什么而已。
享受模式详细定义:传送门
上代码:
package com.array7.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...");
}
}

本文通过一个具体的水果食用实例,介绍了享元模式的概念及其在实际编程中的应用方式。享元模式适用于小类的复用,通常与工厂模式结合使用。文中通过创建一个水果工厂并实现不同种类水果的食用操作,展示了如何利用享元模式来提高代码效率。
704

被折叠的 条评论
为什么被折叠?



