享元模式
享元模式(Flyweight Pattern)用于减少创建对象的数量,以减少内存占用和提高性能。这种模式尝试重用现有的细粒度对象,而不是每次都重新创建新的对象。享元模式特别适用于大量相似对象的场景,这些对象的状态可以被外部状态共享。
案例
设计一个足道店,服务员可以重复提供服务
java
public abstract class AbstractWaiter {
Integer id;
String name;
boolean canService;
public AbstractWaiter(Integer id,String name){
this.id = id;
this.name = name;
canService = true;
}
public abstract void service();
public abstract void end();
}
java
public class Waiters extends AbstractWaiter{
public Waiters(Integer id, String name) {
super(id, name);
}
@Override
public void service() {
System.out.println(id + ":开始服务");
this.canService = false;
}
@Override
public void end() {
System.out.println(id + ":结束服务");
this.canService = true;
}
}
java
public class ZuDao {
private Map<Integer,Waiters> poll = new HashMap<>();
{
Waiters zhangsan = new Waiters(1, "zhangsan");
Waiters lisi = new Waiters(2, "lisi");
poll.put(1,zhangsan);
poll.put(2,lisi);
}
public Waiters getWaiter(Integer id){
Waiters waiter = poll.get(id);
if(waiter != null && waiter.canService){
return waiter;
}
return null;
}
}
测试:
java
public class Main {
public static void main(String[] args) {
ZuDao zuDao = new ZuDao();
Waiters waiter = zuDao.getWaiter(1);
waiter.service();
Waiters waiter1 = zuDao.getWaiter(2);
waiter1.service();
Waiters waiter2 = zuDao.getWaiter(1);
System.out.println(waiter2);
waiter.end();
waiter1.end();
}
}