Java Reference
In-Depth Information
Flyweight
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 A.171 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 A.172 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 A.173 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. }
Since these two classes are used to track the overall state of the application, they are managed by a StateFactory
class that creates both objects and provides them on demand.
Example A.174 StateFactory.java
1. public class StateFactory {
2. public static final State CLEAN = new CleanState();
3. public static final State DIRTY = new DirtyState();
4. private static State currentState = CLEAN;
 
Search WWH ::




Custom Search