import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; public class CommandLogger { public static void main(String[] args) throws Exception { // Write a list of commands for later use String fn = "logfile"; FileOutputStream bytesToDisk = new FileOutputStream(fn); ObjectOutputStream objectToBytes = new ObjectOutputStream(bytesToDisk); // Imagine commands are some important logged transaction WorkCommand commandWork = new DomesticEngineer(); WorkCommand commandPol = new Politician(); WorkCommand commandProg = new Programmer(); // Create a list to save for later use ArrayList allCommands = new ArrayList(); allCommands.add(commandWork); allCommands.add(commandPol); allCommands.add(commandProg); // add more, mix 'em up // Save the list to a file for later use objectToBytes.writeObject(allCommands); objectToBytes.close(); /////////////////////////////////////////////////////////// String fileName = "logfile"; FileInputStream diskToStreamOfBytes = null; ObjectInputStream bytesToObjects = null; diskToStreamOfBytes = new FileInputStream(fileName); bytesToObjects = new ObjectInputStream(diskToStreamOfBytes); ArrayList list = (ArrayList) bytesToObjects .readObject(); bytesToObjects.close(); for (WorkCommand command : list) command.execute(); } } // Purpose. Command design pattern - decoupling producer from consumer interface WorkCommand { void execute(); } class DomesticEngineer implements WorkCommand, Serializable { public void execute() { System.out.println("take out the trash"); } } class Politician implements WorkCommand, Serializable { public void execute() { System.out.println("take money from the rich, take votes from the poor"); } } class Programmer implements WorkCommand, Serializable { public void execute() { System.out.println("sell the bugs, charge extra for the fixes"); } }