“泄漏此"从设计的角度来看 [英] "Leaking this" from a Design Standpoint

查看:48
本文介绍了“泄漏此"从设计的角度来看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

警告:在构造函数中泄漏"this"

Warning: Leaking "this" in constructor

我一直遇到这个问题,并且感到and是因为我的设计是错误的或不是最佳的.

I keep running into this, and I have a nagging feeling that it's because my design is wrong or not optimal.

我了解到此警告引起了我的注意,即我允许访问可能未完全初始化的对象.

I understand that this warning is bringing to my attention the fact that I am allowing access to an object that is potentially not fully initialized.

比方说,我需要一个具有HAS且需要一个列表的框架(Frame(列表列表)).在列表中,我可能想要执行诸如add()之类的操作.为了确保Frame对List的了解尽可能少(只有它对List有了解),我想从List中访问包含的Frame(List是否有Frame?).这似乎有点愚蠢,但是我有2+种List的实现,它们将以不同的方式使用Frame.

Let's say that I need a Frame that HAS and requires a List (Frame(List list)). In List, I might want to do something such as add(). In order to make sure Frame knows as little about List as possible (only that it has one), I would want to access the containing Frame from the List (List HAS a Frame?). This seems a little silly, but I have 2+ implementations of List that will use Frame in different ways..

为确保正确使用我的代码,我将在List的构造函数中需要一个Frame. 我还需要在Frame的构造函数中使用一个List,因为它必须有一个:

To ensure that my code is used properly, I would require a Frame in the constructor of List. I would also require a List in the constructor of Frame, as it MUST have one:

public abstract class Frame {
    private final List list;

    public Frame(List list) {
        this.list = list;
        list.setFrame(this);
    }
}

public abstract class List {
    private Frame frame;

    protected final void setFrame(Frame frame) {
        this.frame = frame;
    }
}

那么,这是一个不好的设计吗,还是我应该真正创建一个能做到这一点的中间支架,或者甚至将支架留给用户使用?

So, is this bad design, or should I really create some intermediate scaffolding that does this, or even leave the scaffolding to the user?

谢谢!

推荐答案

介绍一种工厂方法:

public static Frame createFrame(List list) {
    Frame frame = new Frame(list);
    list.setFrame(frame);
}

private Frame(List list) {
    this.list = list;
}

这不会泄漏此信息,并且始终确保所有配置都正确,而无需每个调用者都记住初始化关联的两端.

This does not leak this, and always makes sure everything is configured correctly without the need for every caller to remember initializing both sides of the association.

这篇关于“泄漏此"从设计的角度来看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆