享元模式
定义
提供了减少对象数量从而改善应用所需的对象结构的方式
运用共享技术有效地支持大量细粒度的对象
其实实际上就是缓存的使用
类型:结构型
使用场景
(1)常用于系统底层开发,以便解决系统的性能问题,
(2)系统需要大量相似对象,需要缓冲池的场景,比如java的integer就是使用的享元模式
优缺点
优点:
减少对象的创建,降低内存中对象的数量,降低系统的内存,提供利用率
减少内存之外的其他资源的占用
缺点:
需要关注线程安全
使系统、程序的逻辑复杂化
Demo
public interface ItemView {
void showView();
}
public class ConcreteItemView implements ItemView {
private String type;
public void setType(String type) {
this.type = type;
}
@Override
public void showView() {
System.out.println("ItemView的显示样式"+type);
}
}
public class ItemViewFactory {
static HashMap<String, ConcreteItemView> ITEMVIEWS = new HashMap<>();
public static ConcreteItemView getItemView(String type) {
ConcreteItemView concreteItemView = ITEMVIEWS.get(type);
if (concreteItemView == null) {
concreteItemView = new ConcreteItemView();
concreteItemView.setType(type);
ITEMVIEWS.put(type,concreteItemView);
}
return concreteItemView;
}
}
测试类
public class Test {
public static void main(String[] args) {
ConcreteItemView concreteItemView=ItemViewFactory.getItemView("List列表");
ConcreteItemView concreteItemView2=ItemViewFactory.getItemView("Grid栅格");
ConcreteItemView concreteItemView3=ItemViewFactory.getItemView("List列表");
if (concreteItemView==concreteItemView3){
concreteItemView.showView();
}
}
}
ps:享元模式主要就是通过缓存来减少资源的创建