1. 理念
- 用于减少创建对象的数量,以减少内存占用和提高性能
- 尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象
2. Coding
- 频繁需要创建的对象,在池子中通过map来保存
- 数据库连接池,线程池,都是享元模式的经典利用
package com.nike.erick.flyweight;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
AnimalPool.getAnimal("cat");
AnimalPool.getAnimal("cat");
}
}
class AnimalPool {
private static Map<String, Animal> zoo = new HashMap<>();
public static Animal getAnimal(String type) {
if (zoo.containsKey(type)) {
System.out.println("从圆子里面拉个动物出来" + type);
return zoo.get(type);
} else {
if (type == "cat") {
Cat cat = new Cat();
zoo.put("cat", cat);
return cat;
} else if (type == "dog") {
Dog dog = new Dog();
zoo.put("dog", dog);
return dog;
} else {
throw new IllegalArgumentException("参数错误");
}
}
}
public static int getPoolSize() {
return zoo.size();
}
}
class Cat extends Animal {
@Override
void eat() {
System.out.println("猫吃鱼");
}
}
class Dog extends Animal {
@Override
void eat() {
System.out.println("狗吃肉");
}
}
abstract class Animal {
abstract void eat();
}