开发者

Best OO way to handle "cancel button"

开发者 https://www.devze.com 2023-03-07 23:43 出处:网络
I always wondered what\'s the best way of handling a cancel button in a more OO way. In the hurry I always end up putting the ugly checking of a boolean form property if the button was canceled of not

I always wondered what's the best way of handling a cancel button in a more OO way. In the hurry I always end up putting the ugly checking of a boolean form property if the button was canceled of not.

The thing is that way makes the code dirty, having a lot of "cancel checks" between logic that matters.

I always get to something like this:

void doLogic()
{
     checkIfIsCancelled();
     callOtherFunction();

     checkIfIsCancelled();
     callAnotherFunction();
开发者_C百科
     checkIfIsCancelled();
     callAnotherFunction();

     checkIfIsCancelled();
     callAnotherFunction();
}

I hope I was clear enough. I just want a neater way to do this :)


A proper way to handle this is the strategy pattern, where you have a default strategy where you do the normal processing and you have a Cancelled strategy.

Canceling changes the strategy to the cancelledStrategy that does nothing but some cleanup. The next call will go to the cancelledStrategy.

In this way even the cleanup is pretty straight forward because you know exactly where in the flow it was cancelled.

Another possible solution (but very dependent on your situation) would be the state pattern, but if you only need it for canceling it creates a lot of overhead.


it would REALLY help to know what GUI kit you're using here. Just from this it's impossible to know if you're taking about a windows, linux or mac machine. Add to that I can't think of a single GUI that that would function in this manner.

Most GUI's operate with a 'callback' pattern Widgets(buttons, menus, listboxes etc) are created and your code attaches a 'callback', a piece code or object&method that is executed when an action is performed on a widget.

In java for example:

Button b = JButton("Push") ;
listener = new ActionListener()_ {
    public void actionPerformed(ActionEvent e) {
        System.out.println("I was pushed!") ;
    }
} ;
b.addActionListener(listener)

Arranges for the message "I was pushed!" to be printed when the button is pressed. Of course this thin examples omits all of the work you need to do to setup your window, populate this widget etc.


1st what comes to mind is http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern but I'm not sure, it's good here.


You can use the command pattern alongwith a stack to implement multi level undo support.

0

精彩评论

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

关注公众号