概念:
享元模式:Use sharing to support large numbers of fine-gained object efficiently.使用享元模式可以有效地支持大量的细粒度额对象。这中英文翻译过来的定义,是不是看的一头雾水。简单来说就是结合工厂模式的对象池。看代码,其实倒不是很难。实现:
享元对象(接口就定义了一个reader的方法,就不写了)1 public class Book implements IBook { 2 public Book(String type){ 3 this.type = type; 4 } 5 6 private String type; 7 8 @Override 9 public void reader() {10 System.out.println("我正在读"+type+"书");11 }12 }
1 public class BookFactory { 2 private static Mappool = new HashMap<>(); 3 4 private BookFactory(){} 5 6 public static Book getBook(String type){ 7 Book book = pool.get(type); 8 if(book ==null){ 9 book = new Book(type);10 pool.put(type,book);11 }12 return book;13 }14 }