开发者

Strategy Pattern - Input from UI

I have a very simple question.开发者_高级运维 I have a User interface which prompts the user to choose "Option A" or "Option B" (Actual option buttons). Once the user chooses I call in to a repository that connects to a database to get some data.

Option A would require a certain type of query and Option B would generate different. Without getting to specifics, I have implemented a strategy pattern called OptionAStrategy and OptionBStrategy that would generate the correct query so that repository can use the query.

Now the question is how do I pass the fact that user choose "Option A" or B. I can pass the actual string say "Option A" or "Option B" and pass that string to a StrategyFactory to instantiate the correct OptionStartegy. But is that a good practice else

How does the UI communicate a chosen UI option so that a strategy factory can correctly instantiate the correct instance of strategy? assuming strategy sits at repositories level

Thanks in Advance Cheers

Bump: No answers - low views :-(


You could define your strategies as implementations of an Action or ActionListener and then attach them to a specific UI element, such as a JButton. Upon user click, that action would be executed.
For example, using Java Swing:

final Action optionA = new AbstractAction("Option A") {
    public void actionPerformed(ActionEvent e){
        // option A code
    }
};
final JButton optionAButton = new JButton(optionA);
// add button to UI
  • How to Use Actions
  • AbstractAction

A benefit of using Swing actions is that many of the UI components can be constructed from an Action, allowing you to provide multiple UI mechanisms of varying style that all perform the same function.

The next step would be to create factories for providing these different Actions to some sort of application-specific controller that would then inject them into the UI components.


You need to have context and Strategy interface. In your context you can choose you if/else to choose the appropriate strategy or use factory class to get you startegy. See it Here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜