220 likes | 385 Views
Computer Science 313 – Advanced Programming Topics. Lecture 25: Advanced Command patterns. Command Pattern Intent. Decouples action invocation from its execution Write classes independent of operation executed Encapsulate operation as an object
E N D
Computer Science 313 – Advanced Programming Topics Lecture 25:Advanced Command patterns
Command Pattern Intent • Decouples action invocation from its execution • Write classes independent of operation executed • Encapsulate operation as an object • Makes possible buffering or logging operations • Undo-ing operations can be supported with ease • Code will support combining or extending actions
Command Pattern Intent • Decouples action invocation from its execution • Write classes independent of operation executed • Encapsulate operation as an object • Makes possible buffering or logging operations • Undo-ing operations can be supported with ease • Code will support combining or extending actions
Command Pattern Example public class Quitter implements ActionListener {public void actionPerformed(ActionEvent e) { System.exit(0);} } public class Bob extends JFrame {⁞JMenuItem quit = new JMenuItem(“Quit”);quit.addActionItem(new Quitter());⁞ }
Command Pattern Example public class Quitter implements ActionListener {public void actionPerformed(ActionEvent e) { System.exit(0);;} } public class Bob extends JFrame {⁞JMenuItem quit = new JMenuItem(“Quit”);quit.addActionItem(new Quitter());⁞ } Client
Command Pattern Example public class Quitter implements ActionListener {public void actionPerformed(ActionEvent e) { System.exit(0);} } public class Bob extends JFrame {⁞JMenuItem quit = new JMenuItem(“Quit”);quit.addActionItem(new Quitter());⁞ } Command
Command Pattern Example public class Quitter implements ActionListener {public void actionPerformed(ActionEvent e) {System.exit(0);} } public class Bob extends JFrame {⁞JMenuItem quit = new JMenuItem(“Quit”);quit.addActionItem(new Quitter());⁞ } ConcreteCommand
Command Pattern Example public class Quitter implements ActionListener {public void actionPerformed(ActionEvent e) {System.exit(0);} } public class Bob extends JFrame {⁞JMenuItem quit = new JMenuItem(“Quit”);quit.addActionListener(new Quitter());quit.doClick();⁞ } Invoker
Command Pattern Example public class Quitter implements ActionListener {public void actionPerformed(ActionEvent e) {System.exit(0);} } public class Bob extends JFrame {⁞JMenuItem quit = new JMenuItem(“Quit”);quit.addActionItem(new Quitter());⁞ } Receiver
Delaying Gratification • Command pattern must encapsulate actions • Can delay executing commands until should act • GUI adds to Queue & execute Commands in FIFO order • Enables splitting action execution & creation • In Java, sometimes see delay between cause & effect • Prevent executing more actions if code contains bugs • Even if listener throws exception, program continues
Information Logs • Track Commands executed, by keeping a log • If multiple Invokers, Commands must refer to log • Keep only one log at a time to record order • To keep this log,could pass references everywhere • Switching the log causes problems, however • Solution: Make Log a singleton class
Keeping a Log • Several ways to log executed Commands • If queued, print Commandbefore executing • Rely on Command to print self in execute() • Make Invoker call store() method in Command • Which is the best choice depends on… • System implementation & where changes expected • Exactly which of the details to be logged • Classes most reliable coders on team were writing
Improving Performance • Many modern CPUs contain multiple cores • Complete execution unit in each core on chip • Processor executes multiple tasks simultaneously • Need to take advantage to maximize performance • Number of cores varies by processor • Single core in older or cheaper processors • Can also find dual-core, quad-core, & more • One job per core provides best performance • Must write your code to scale to available cores
Commands to the Rescue • Simple solution using the command pattern • Interface for Command already in Java public interface Runnable { public void run();} • Invoker classes available as part of Java, also • In your code, can get instance of this class using Executor.newFixedThreadPool()orExecutor.newScheduledThreadPool()
How Thread Pools Work • Creates pool of threads to perform work • Each of these threads execute command at a time • Executes next command after first is completed • Optimize performance creating thread per core • ConcreteCommand classes left to write • Could be any class implementing Runnable • Invoker calls run() method in instances
How Thread Pools Work • Creates pool of threads to perform work • Each of these threads execute command at a time • Executes next command after first is completed • Optimize performance creating thread per core • ConcreteCommand classes left to write • Could be any class implementing Runnable • Invoker calls run() method in instances • Textbook example of Command Pattern
Thread Pool Example public class Lin implements Runnable {public void run() { for (long num = 0; num < 50; num++)System.out.println(“Lin: ” + num);} } public class Exp implements Runnable {public void run() { for (long num = 1; num < 250; num*=2) {System.out.println(“Exp: ” + num);} }
Thread Pool Example public static void main(String[] args){Runnable command1 = new Lin();Runnable command2 = new Lin();Runnable command3 = new Exp();ExecutorServicepool =Executors.newFixedThreadPool(2);pool.execute(command1);pool.execute(command2);pool.execute(command3);pool.shutdown();pool.awaitTermination(21,TimeUnit.DAYS); }
Thread Pool Results • Thread pool started with 1, 2, & 3 threads:
Transaction-Based System • Databases also big users of command pattern • Can easily replicate actions in normal programs • Transactions are used to make DBs work • Gather set of changes into single action • Makes all changes in transactions as single action • Result either ALL changes or NO changes made
Transaction-Based System • Transactions are just a party! • Very, very hot area of research also • Many organizations looking to generalize this • Example of MacroCommands in wide use • Command places individual changes into group • Apply changes when MacroCommandexecuted • Needs checks to ensure one macro run at a time
For Next Class • Lab #5 due by 11:59AM next Friday • Get busy restructuring code so ready for real world • Will have time in lab, but due before next week’s lab • Next lecture on Adapter Pattern (p. 235-253) • Fir square peg in round hole using code; can we do it? • What does this have to do with legacy code? • No standard electrical plug; why could this be?