Java Reference
In-Depth Information
Strategy (page 114) - The Strategy pattern is another pattern that can benefit from being implemented as a
Flyweight.
Example
Note:
For a full working example of this code example, with additional supporting classes and/or a RunPattern class,
see “ Flyweight ” on page 477 of the “ Full Code Examples ” appendix.
This example uses the Flyweight pattern to share common State objects within the PIM. The State pattern
example used state objects to edit and store information for a set of Appointments . In this example, the States
will be used to manage edits and save for multiple collections of objects.
The State interface provides standard behavior for all application states. It defines two basic methods, edit and
save .
Example 3.25 State.java
1. package flyweight.example;
2.
3. import java.io.File;
4. import java.io.IOException;
5. import java.io.Serializable;
6.
7. public interface State {
8. public void save(File f, Serializable s) throws IOException;
9. public void edit();
10. }
State is implemented by two classes—CleanState and DirtyState. This example uses these classes to track the
state of multiple objects, so the classes have additional support to track which items need to be refreshed.
Example 3.26 CleanState.java
1. import java.io.File;
2. import java.io.FileOutputStream;
3. import java.io.IOException;
4. import java.io.ObjectOutputStream;
5. import java.io.Serializable;
6.
7. public class CleanState implements State{
8. public void save(File file, Serializable s, int type) throws IOException{ }
9.
10. public void edit(int type){
11. StateFactory.setCurrentState(StateFactory.DIRTY);
12. ((DirtyState)StateFactory.DIRTY).incrementStateValue(type);
13. }
14. }
Example 3.27 DirtyState.java
1. package flyweight.example;
2.
3. import java.io.File;
4. import java.io.FileOutputStream;
5. import java.io.IOException;
6. import java.io.ObjectOutputStream;
7. import java.io.Serializable;
8.
9. public class DirtyState implements State {
10. public void save(File file, Serializable s) throws IOException {
11. //serialize s to f
12. FileOutputStream fos = new FileOutputStream(file);
13. ObjectOutputStream out = new ObjectOutputStream(fos);
14. out.writeObject(s);
15. }
16.
17. public void edit() {
18. //ignored
19. }
20. }
Search WWH ::




Custom Search