I try to understand the difference between stateless and stateful.
As an example i take the Java LayoutManager. Normally i cannot use an instance for example of the BorderLayout for more than one container. I think in a stateful strategy, the Context pass itself as an argument to Strategy operation. So that the strategy can reach all data which is needed for the strategy algorithm.
I have a Code Snippet of a stateful strategy. I think here the context is "creation of the panel" for which we have different strategies.
public class LayoutComparer extends JFrame {
private LayoutManager layout;
private String title;
public static void main(String[] args) {
JFrame f = new LayoutComparer();
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
static int counter = 0;
JPanel createPanel(LayoutManager layout, String title) {
this.layout = layout;
this.title = title;
JPanel p = new JPanel();
p.setLayout(layout);
p.add(new JButton("Click " + counter++), "West");
p.add(new JButton("Click " + counter++), "Center");
p.add(new JButton("Click " + counter++), "East");
p.setBorder(BorderFactory.createTitledBorder(title));
return p;
}
LayoutComparer() {
setTitle("Layout Manager Test");
setLayout(new GridLayout(1, 2));
LayoutManager m;
m = new java.awt.FlowLayout();
// m = new java.awt.BorderLayout();
add(createPanel(m, "Left"));
// pack();
add(createPanel(m, "Right"));
}
}
Aucun commentaire:
Enregistrer un commentaire