团建去吃火锅了,回来没时间写笔记,发篇以前写过的设计模式把
享元模式是一个重用现有对象来减少内存占用和提高性能的模式,有点类似单例模式,但是享元可以创建多个不同的对象。主要思路是用一个 HashMap 来存放已经创建的对象(每个对象有唯一标识),每次创建对象前先查找 HashMap。String 的缓存池,数据库的数据池都是享元模式的体现
享元模式的组成:
public interface Animal { void say(String say); }
public class Dog implements Animal { private String name; public Dog(String name) { this.name = name; } @Override public void say(String say) { System.out.println("I am dog " + name + ", i want to say: " + say); } }
public class AnimalFactory { private static final HashMap<String, Animal> hashMap = new HashMap<>(); public static Animal getAnimal(String name) { if(!hashMap.containsKey(name)) { Animal animal = new Dog(name); hashMap.put(name, animal); } return hashMap.get(name); } }
public static void main(String[] args) { Animal animal1 = AnimalFactory.getAnimal("1"); Animal animal2 = AnimalFactory.getAnimal("2"); Animal animal3 = AnimalFactory.getAnimal("1"); animal1.say("1"); // I am dog 1, i want to say: 1 animal2.say("2"); // I am dog 2, i want to say: 2 animal3.say("3"); // I am dog 1, i want to say: 3 }