定义:主要用于减少创建对象的数量,以减少内存占用和提高性能。
个人理解:各种池,常量池(String为代表),线程池,数据库连接池等等。
UML图解:
优点:大大减少对象的创建,降低系统的内存,效率及空间利用率大大提高。
缺点:会增加出来很多池,提高了系统的复杂性。
代码:
class Bullet{
public UUID id = UUID.randomUUID();
boolean living = true;
@Override
public String toString() {
return "Bullet{" +
"id=" + id +
'}';
}
}
public class BulletPool {
List<Bullet> bullets = new ArrayList<>();
{
for(int i=0; i<5; i++) bullets.add(new Bullet());
}
public Bullet getBullet() {
for(int i=0; i<bullets.size(); i++) {
Bullet b = bullets.get(i);
if(!b.living) return b;
}
return new Bullet();
}
public static void main(String[] args) {
BulletPool bp = new BulletPool();
for(int i=0; i<10; i++) {
Bullet b = bp.getBullet();
System.out.println(b);
}
}
}
总结:常用的设计模式,应该配合各种池去理解。