设计模式——享元模式

享元模式是一种结构型设计模式,通过缓存技术减少大量相似对象的创建,以优化性能。适用于系统底层开发和需要缓冲池的场景,如Java中的Integer。尽管能降低内存占用,但可能增加系统复杂性和线程安全问题。
摘要由CSDN通过智能技术生成

享元模式

定义

提供了减少对象数量从而改善应用所需的对象结构的方式
运用共享技术有效地支持大量细粒度的对象
其实实际上就是缓存的使用

类型:结构型

使用场景

(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:享元模式主要就是通过缓存来减少资源的创建

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值