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"));
}
}
In short "stateful" means that the instance that does some operation (in your case the LayoutManager) holds some state beyond the scope of the operation that is to be done. If it holds state during the operation I'd still consider it stateless but not necessarily threadsafe.
That said a "stateless" instance would not hold any "persistent" state (beyond the scope of the current operation) and ideally not any state at all, thus making it more threadsafe (there might be other things that need to be considered to make it fully threadsafe).
In the case of a LayoutManager you need to keep in mind that it will not only be using while creating components but also during the lifetime of the component for resizing purposes etc.
A LayoutManager that doesn't require any special setup or which can use a common setup (e.g. FlowLayout) might be consideres stateless enough (I don't know what it uses internally) but managers like BorderLayout
require specific configuration (e.g. the north, south, center etc. components) which needs to be kept/hold thus making that LayoutManager stateful.