多例模式 multiton
- 在单例模式中,每一个类我们只能获取它的一个实例. 而在多例中,我们可以获取该类的有限个实例,是创建型的设计模式,
public enum FruitType {
APPLE, BANANA;
}
public class Fruit {
private String name;
private Fruit(String name) {
this.name = name;
}
private static ConcurrentHashMap<FruitType,Fruit> fruits;
static {
fruits.put(APPLE,new Fruit("pinguo"));
fruits.put(BANANA,new Fruit("xiangjiao"));
}
public static Fruit getFruit(FruitType fruitType){
return fruits.get(fruitType);
}
}
public static void main(String[] args) {
Fruit apple = Fruit.getFruit(FruitType.APPLE);
Fruit banana = Fruit.getFruit(FruitType.BANANA);
}
- 在上述案例中,对于Fruit类, 只有通过getFruit()方法才能够获取两种已经实例化好的水果
- 多例模式在获取有限多个类实例的时候很有帮助