团建去吃火锅了,回来没时间写笔记,发篇以前写过的设计模式把
1. 享元模式
享元模式是一个重用现有对象来减少内存占用和提高性能的模式,有点类似单例模式,但是享元可以创建多个不同的对象。主要思路是用一个 HashMap 来存放已经创建的对象(每个对象有唯一标识),每次创建对象前先查找 HashMap。String 的缓存池,数据库的数据池都是享元模式的体现
享元模式的组成:
- Flyweight: 享元对象(下面举例的dog对象)
- IntrinsicState: 共享内部状态(name 是共享的)
- ExtrinsicState: 每个享元对象的外部状态各不同(say 是不同的)
2. 过程
2.1 享元接口
public interface Animal {
void say(String say);
}
2.2 享元对象
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);
}
}
2.3 享元工厂
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);
}
}
2.4 测试
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
}