开发者

How to release resource if the resource is passed on to a serial of objects?

开发者 https://www.devze.com 2022-12-22 15:18 出处:网络
I am implement a pipeline pattern, the resource is passed on to a serial of objects that wi开发者_JAVA技巧ll process the resource, when one object is done using the resource it passes it on to the suc

I am implement a pipeline pattern, the resource is passed on to a serial of objects that wi开发者_JAVA技巧ll process the resource, when one object is done using the resource it passes it on to the successor, so when and which object to release the resource?


You mean with something like chain of responsability pattern (or one variant)? If yes, I guess the last processing object could release the resource:

    public void process( Resource rsrc )
    {
        writeMessage( msg );

        if ( next != null )
        {
            next.process( rsrc );
        }
        else
        {
            // release resource
        }
    }

But your question wasn't very clear to me, so I'm not sure I answered your question exactly.

EDIT

I assumed you had some rather complex scenario and your pipeline didn't return in a trivial way (e.g if it's asynchronous). But as suggested in the other answers, if you can create the resource, fire the chain of responsibility and then release the resource, it's of course the easiest way:

Resource rsrc = new Resource();
chain.process( rsrc );
rsrc.release();


The caller who passes the resource to the pipe. It allocates the resource and starts processing, so it should clean it up.

If the control is never returned to the caller, you could use a terminator at the end of the pipe (but this terminator should not be responsible for anything else).

Making one the pipe objects responsible sounds like an antipattern, because it means tighter coupling and is harder to maintain.


It sounds as though you're implementing what I know as the Chain of Responsibility pattern or something very similar.

In which case, I'd suggest releasing the resource from wherever you initiate the work of the chain, rather than delegating that responsibility to one of the processors within the chain.


I'd suggest you have a look at the "Unit of Work" pattern.

In other words, make the data, objects and the resource itself part of a single object that your pipeline passes along. Make the unit of work expose a release method which will take care of rollback/release/commit all pending work (possibly distinguishing if it was due to an Abend).

This release method will be called by your last step in the pipeline (if everything goes well) or by the catch/finally part of your intermediate steps if something breaks.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号