0%

设计模式-享元模式

享元模式(Flyweight pattern),属于结构型模式,可以减少创建对象的数量,从而减少堆内存占用和提高效率。

结构


涉及到了两个角色,flyweight(享元类)、flyweightFactory(享元工厂)

享元类

flyweight,享元类可以被多个对象共享,示例如下

1
2
3
4
5
6
7
8
9
public class BookOrder {
private String name;
BookOrder(String name){
this.name = name;
}
public void print(){
System.out.println("卖了一本书,书名为" + name);
}
}

享元工厂

flyweightFactory,用数据池(如Map)管理所有享元对象,存在则返回,不存在则新增。示例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class BookOrderFactory {
private Map<String, BookOrder> pool;
public BookOrderFactory(){
this.pool = new HashMap<>();
}
public BookOrder getBookOrder(String bookname){
BookOrder bookOrder = pool.get(bookname);
if(bookOrder == null){
bookOrder = new BookOrder(bookname);
pool.put(bookname, bookOrder);
}
return bookOrder;
}
}

客户端

客户端必须通过享元工厂创建享元对象,示例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Client {
public static void main(String[] args) {
BookOrderFactory factory = new BookOrderFactory();
List<BookOrder> list = new ArrayList<>();
list.add(factory.getBookOrder("三国"));
list.add(factory.getBookOrder("水浒"));
list.add(factory.getBookOrder("三国"));
list.add(factory.getBookOrder("水浒"));
list.add(factory.getBookOrder("水浒"));
list.add(factory.getBookOrder("三国"));
for(BookOrder order : list){
order.print();
}
}
}

好处:本来需要创建6个对象,现在只需要创建2个享元对象

完整代码

完整代码已上传,项目地址https://github.com/yuan0824/DesignPattern

参考资料