SlideShare une entreprise Scribd logo
1  sur  25
Design patterns...Session N#2 Leonid M.
Design Patterns ,[object Object]
State
NullObjectPuzzle questions Mini seminar #1: Content
Each pattern describes a problem which occursover and over again in our environment, and then describes the core of the solutionto that problem, in such a way that you can use this solution a million timesover, without ever doing it the same way twice  Christopher Alexander, Sara Ishikawa, MurraySilverstein, Max Jacobson,Ingrid Fiksdahl-King, and ShlomoAngel.A Pattern Language. Oxford UniversityPress, NewYork, 1977. Design Pattern Repetitioest mater studiorum
Command pattern
Synonyms: Action, Transaction Intent: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. Command
There are two extremes that a programmer must avoid when using this pattern: The command is just a link between the receiver and the actions that carry out the request The command implements everything itself, without sending anything to the receiver. We must always keep in mind the fact that the receiver is the one who knows how to perform the operations needed, the purpose of the command being to help the client to delegate its request quickly and to make sure the command ends up where it should. The intelligence of a command
Command decouples the object that invokes the operation from the one that knows how to perform it. Commands are first-class objects. They can be manipulated and extended like any other object. You can assemble commands into a composite command.  It's easy to add new Commands, because you don't have to change existing classes. Consenquencies
Decoupling Menu Application add(Document)  Menu Item onClick() Save Command document->save() execute() command->execute() Action
Code next door (Swing) import java.awt.Component; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; class ExitAction extends AbstractAction { public ExitAction() { super("exit");     } public void actionPerformed(ActionEvent e) { System.exit(0);     } } class ShowDialogAction extends AbstractAction { public ShowDialogAction() { super("show dialog");     } public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog((Component) e.getSource(),  "An action generated this dialog");     } } public class Test extends JFrame { public static void main(String args[]) {         Test frame = new Test(); frame.setTitle("Swing Actions"); frame.setSize(500, 400); frame.setLocation(400, 200); frame.show();     } public Test() { JMenuBarmb = new JMenuBar(); JMenufileMenu = new JMenu("File"); fileMenu.add(new ShowDialogAction()); fileMenu.add(new ExitAction()); mb.add(fileMenu); setJMenuBar(mb);     } }
Undo support Macro-commands Queuing requests Logging requests Specific problems /implementation
Undo support -addCommand() -undo() -execute() -canUndo() -undo() Please, undo the last one. It caused problems! Can undo?  Take back, undo, place in queue client Command manager
Code next door (Swing)#Swing’s undo mechanism class diagram
Macro-commands
 /**      * Calculates the proper constraint for a child being added. createAddCommand is called afterwards.      */     @Override protected Command getAddCommand(Request generic) {         // cast request to ChangeBoundsRequest ChangeBoundsRequest request = (ChangeBoundsRequest) generic;         // get all Edit Parts of request List editparts = request.getEditParts();         // create a new CompoundCommand CompoundCommand res = new CompoundCommand(); Rectangle r;         Object constraint;         // for each Edit Part set constraint for (IteratorepIt = editparts.iterator(); epIt.hasNext();) { GraphicalEditPart part = (GraphicalEditPart) epIt.next();             r = part.getFigure().getBounds().getCopy();             // convert r to absolute from childpart figure part.getFigure().translateToAbsolute(r);             r = request.getTransformedRectangle(r);             // convert this figure to relative getLayoutContainer().translateToRelative(r); getLayoutContainer().translateFromParent(r); r.translate(getLayoutOrigin().getNegated());             constraint = getConstraintFor(r); if ((part instanceofAttributeEditPart) || (part instanceofMethodEditPart)                     || (part instanceofSlotEditPart)) { return null;             } else { res.add(createAddCommand(part, constraint));             }         } return res.unwrap();     } Code next door (Gef, Eclipse)
Queuing requests User commands are added to the queue This gives an effective way to limit computations to a fixed numbers of threads  Threads removes commands from the queue by on one, calls execute(). Once complete, go back for a new command object
java.lang.Runnable ,[object Object],java.util.concurrent.Callable<V> - Sample invoker: ExecutorService#submit(), ExecutorService#invokeXxxx() Code next door (JDK)
Logging requests store() store() load() load() store() load() execute() execute() execute() execute() execute() execute()
Also Known as: 	Stub, Active Nothing Intent:  ,[object Object]
The Null Object Pattern provides intelligent do nothing behavior, hiding the details from its collaborators.NullObject pattern Invoker <<Object interface>> Object request() RealObject NullObject() request() request() { // do nothing; }
Null objects can be used in place of real objects when the object is expected to do nothing.  Makes client code simple. (reduces branching) Encapsulates the do nothing code into the null object.  Makes the do nothing code in the null object easy to reuse.  Makes the do nothing behavior difficult to distribute or mix into the real behavior of several collaborating objects.  Can be difficult to implement if various clients do not agree on how the null object should do nothing as when your AbstractObject interface is not well defined. Always acts as a do nothing object. The Null Object does not transform into a Real Object. Consenquencies
Null Object and Factory 	The Null Object design pattern is more likely to be used in conjunction with the Factory pattern. The reason for this is obvious: A Concrete Classes need to be instantiated and then to be served to the client. The client uses the concrete class. The concrete class can be a Real Object or a Null Object.  Null Object and Template Method 	The Template method design pattern need to define an abstract class that define the template and each concrete class implements the steps for the template. If there are cases when sometimes template is called and sometimes not then, in order to avoid the checking a Null Object can be use to implement a Concrete Template that does nothing. Removing old functionality 	The Null Object can be used to remove old functionality by replacing it with null objects. The big advantage is that the existing code doesn't need to be touched. Specific problems /implementation
NullAppender (log4j) java.util.Collections (jdk) ,[object Object]
#emptySet()

Contenu connexe

Tendances

New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
rashmita_mishra
 
Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6
Ray Ploski
 
Object Design - Part 1
Object Design - Part 1Object Design - Part 1
Object Design - Part 1
Dhaval Dalal
 

Tendances (20)

React hooks
React hooksReact hooks
React hooks
 
C questions
C questionsC questions
C questions
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Mockito
MockitoMockito
Mockito
 
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
 
Object Design - Part 1
Object Design - Part 1Object Design - Part 1
Object Design - Part 1
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstitute
 
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
Javantura v2 - Making Java web-apps Groovy - Franjo ŽilićJavantura v2 - Making Java web-apps Groovy - Franjo Žilić
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
 
Javascript closures
Javascript closures Javascript closures
Javascript closures
 

Similaire à 2. Design patterns. part #2

Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Mario Fusco
 
react-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryreact-slides.pdf gives information about react library
react-slides.pdf gives information about react library
janet736113
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems
Eberhard Wolff
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
WO Community
 

Similaire à 2. Design patterns. part #2 (20)

Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
10 Typical Problems in Enterprise Java Applications
10 Typical Problems in Enterprise Java Applications10 Typical Problems in Enterprise Java Applications
10 Typical Problems in Enterprise Java Applications
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
react-slides.pdf
react-slides.pdfreact-slides.pdf
react-slides.pdf
 
react-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryreact-slides.pdf gives information about react library
react-slides.pdf gives information about react library
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
 

2. Design patterns. part #2

  • 2.
  • 4. NullObjectPuzzle questions Mini seminar #1: Content
  • 5. Each pattern describes a problem which occursover and over again in our environment, and then describes the core of the solutionto that problem, in such a way that you can use this solution a million timesover, without ever doing it the same way twice Christopher Alexander, Sara Ishikawa, MurraySilverstein, Max Jacobson,Ingrid Fiksdahl-King, and ShlomoAngel.A Pattern Language. Oxford UniversityPress, NewYork, 1977. Design Pattern Repetitioest mater studiorum
  • 7. Synonyms: Action, Transaction Intent: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. Command
  • 8. There are two extremes that a programmer must avoid when using this pattern: The command is just a link between the receiver and the actions that carry out the request The command implements everything itself, without sending anything to the receiver. We must always keep in mind the fact that the receiver is the one who knows how to perform the operations needed, the purpose of the command being to help the client to delegate its request quickly and to make sure the command ends up where it should. The intelligence of a command
  • 9. Command decouples the object that invokes the operation from the one that knows how to perform it. Commands are first-class objects. They can be manipulated and extended like any other object. You can assemble commands into a composite command. It's easy to add new Commands, because you don't have to change existing classes. Consenquencies
  • 10. Decoupling Menu Application add(Document) Menu Item onClick() Save Command document->save() execute() command->execute() Action
  • 11. Code next door (Swing) import java.awt.Component; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; class ExitAction extends AbstractAction { public ExitAction() { super("exit"); } public void actionPerformed(ActionEvent e) { System.exit(0); } } class ShowDialogAction extends AbstractAction { public ShowDialogAction() { super("show dialog"); } public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog((Component) e.getSource(), "An action generated this dialog"); } } public class Test extends JFrame { public static void main(String args[]) { Test frame = new Test(); frame.setTitle("Swing Actions"); frame.setSize(500, 400); frame.setLocation(400, 200); frame.show(); } public Test() { JMenuBarmb = new JMenuBar(); JMenufileMenu = new JMenu("File"); fileMenu.add(new ShowDialogAction()); fileMenu.add(new ExitAction()); mb.add(fileMenu); setJMenuBar(mb); } }
  • 12. Undo support Macro-commands Queuing requests Logging requests Specific problems /implementation
  • 13. Undo support -addCommand() -undo() -execute() -canUndo() -undo() Please, undo the last one. It caused problems! Can undo? Take back, undo, place in queue client Command manager
  • 14. Code next door (Swing)#Swing’s undo mechanism class diagram
  • 16. /** * Calculates the proper constraint for a child being added. createAddCommand is called afterwards. */ @Override protected Command getAddCommand(Request generic) { // cast request to ChangeBoundsRequest ChangeBoundsRequest request = (ChangeBoundsRequest) generic; // get all Edit Parts of request List editparts = request.getEditParts(); // create a new CompoundCommand CompoundCommand res = new CompoundCommand(); Rectangle r; Object constraint; // for each Edit Part set constraint for (IteratorepIt = editparts.iterator(); epIt.hasNext();) { GraphicalEditPart part = (GraphicalEditPart) epIt.next(); r = part.getFigure().getBounds().getCopy(); // convert r to absolute from childpart figure part.getFigure().translateToAbsolute(r); r = request.getTransformedRectangle(r); // convert this figure to relative getLayoutContainer().translateToRelative(r); getLayoutContainer().translateFromParent(r); r.translate(getLayoutOrigin().getNegated()); constraint = getConstraintFor(r); if ((part instanceofAttributeEditPart) || (part instanceofMethodEditPart) || (part instanceofSlotEditPart)) { return null; } else { res.add(createAddCommand(part, constraint)); } } return res.unwrap(); } Code next door (Gef, Eclipse)
  • 17. Queuing requests User commands are added to the queue This gives an effective way to limit computations to a fixed numbers of threads Threads removes commands from the queue by on one, calls execute(). Once complete, go back for a new command object
  • 18.
  • 19. Logging requests store() store() load() load() store() load() execute() execute() execute() execute() execute() execute()
  • 20.
  • 21. The Null Object Pattern provides intelligent do nothing behavior, hiding the details from its collaborators.NullObject pattern Invoker <<Object interface>> Object request() RealObject NullObject() request() request() { // do nothing; }
  • 22. Null objects can be used in place of real objects when the object is expected to do nothing. Makes client code simple. (reduces branching) Encapsulates the do nothing code into the null object. Makes the do nothing code in the null object easy to reuse. Makes the do nothing behavior difficult to distribute or mix into the real behavior of several collaborating objects. Can be difficult to implement if various clients do not agree on how the null object should do nothing as when your AbstractObject interface is not well defined. Always acts as a do nothing object. The Null Object does not transform into a Real Object. Consenquencies
  • 23. Null Object and Factory The Null Object design pattern is more likely to be used in conjunction with the Factory pattern. The reason for this is obvious: A Concrete Classes need to be instantiated and then to be served to the client. The client uses the concrete class. The concrete class can be a Real Object or a Null Object. Null Object and Template Method The Template method design pattern need to define an abstract class that define the template and each concrete class implements the steps for the template. If there are cases when sometimes template is called and sometimes not then, in order to avoid the checking a Null Object can be use to implement a Concrete Template that does nothing. Removing old functionality The Null Object can be used to remove old functionality by replacing it with null objects. The big advantage is that the existing code doesn't need to be touched. Specific problems /implementation
  • 24.
  • 26. …NullIterator (jdk, internal structures) Code next door
  • 27. public class NullIterator<E> implements Iterator<E> { @Override public booleanhasNext() { return false; // Null implementation returns false indicating iterator is empty } @Override public E next() { throw new NoSuchElementException("Null iterator doesn't contain anything"); } @Override public void remove() { throw new UnsupportedOperationException("Null iterator doesn't support remove operration"); } } Code sample
  • 28. Application: Email spam filtering system. Both HTML and Text formats should be supported. Multiple spam recognition algorithms are present and several could be used simultaneously. Multiple weekly report approaches should be supported: XML, HTML files on filesystem;+ email  with report attachment. Recall Puzzle (prev. sem.)
  • 29.
  • 30. What new considerations come up to mind?
  • 31. How do these changes impact application?
  • 32. How do these impact possible request changes? Pattern puzzle

Notes de l'éditeur

  1. MotivationSometimes it&apos;s necessary to issue requests to objects without knowing anythingabout the operation being requested or the receiver of the request. For example,user interface toolkits include objects like buttons and menus that carry out arequest in response to user input. But the toolkit can&apos;t implement the requestexplicitly in the button or menu, because only applications that use the toolkitknow what should be done on which object. As toolkit designers we have no way ofknowing the receiver of the request or the operations that will carry it out.The Command pattern lets toolkit objects make requests of unspecified applicationobjects by turning the request itself into an object. This object can be storedand passed around like other objects. The key to this pattern is an abstract Commandclass, which declares an interface for executing operations. In the simplest formthis interface includes an abstract Execute operation. Concrete CommandSubclasses specify a receiver-action pair by storing the receiver as anInstance variable and by implementing Execute to invoke the request. The receiverhas the knowledge required to carry out the request.Menus can be implemented easily with Command objects. Each choice ina Menu isan instance of a MenuItem class. An Application class createsthese menus and theirmenu items along with the rest of the user interface.The Application class alsokeeps track of Document objects that a user hasopened.The application configures each MenuItem with an instance of aconcrete Commandsubclass. When the user selects a MenuItem, theMenuItem calls Execute on itscommand, and Execute carries out theoperation. MenuItems don&apos;t know which subclassof Command they use.Command subclasses store the receiver of the request and invokeone ormore operations on the receiver.For example, PasteCommand supports pasting text from the clipboardinto a Document.PasteCommand&apos;s receiver is the Document object it issupplied upon instantiation.The Execute operation invokes Paste onthe receiving Document.OpenCommand&apos;s Execute operation is different: it prompts the userfor a documentname, creates a corresponding Document object, adds thedocument to the receivingapplication, and opens the document. Sometimes a MenuItem needs to execute a sequence of commands.For example, aMenuItem for centering a page at normal size could beconstructed from aCenterDocumentCommand object and aNormalSizeCommand object. Because it&apos;s commonto string commandstogether in this way, we can define a MacroCommand class toallow aMenuItem to execute an open-ended number of commands. MacroCommandisaconcrete Command subclass that simply executes a sequence ofCommands. MacroCommandhas no explicit receiver, because the commandsit sequences define their ownreceiver.In each of these examples, notice how the Command pattern decouplesthe objectthat invokes the operation from the one having theknowledge to perform it. Thisgives us a lot of flexibility indesigning our user interface. An application canprovide both a menuand a push button interface to a feature just by making themenu andthe push button share an instance of the same concrete Command subclass.Wecan replace commands dynamically, which would be useful forimplementingcontext-sensitive menus. We can also support commandscripting by composingcommands into larger ones. All of this ispossible because the object that issuesa request only needs to knowhow to issue it; it doesn&apos;t need to know how the requestwill be carried out.ApplicabilityUse the Command pattern when you want to· parameterize objects by an action to perform, as MenuItem objects did above.You can express such parameterization in a procedural language with acallback function, that is, a function that&apos;s registered somewhere to becalled at a later point. Commands are an object-oriented replacement forcallbacks.· specify, queue, and execute requests at different times. A Command objectcan have a lifetime independent of the original request. If the receiverof a request can be represented in an address space-independent way, thenyou can transfer a command object for the request to a different processand fulfill the request there.· support undo. The Command&apos;s Execute operation can store state for reversingits effects in the command itself. The Command interface must have an addedUnexecute operation that reverses the effects of a previous call to Execute.Executed commands are stored in a history list. Unlimited-level undo andredo is achieved by traversing this list backwards and forwards callingUnexecute and Execute, respectively.· support logging changes so that they can be reapplied in case of a systemcrash. By augmenting the Command interface with load and store operations,you can keep a persistent log of changes. Recovering from a crash involvesreloading logged commands from disk and reexecuting them with the Executeoperation.· structure a system around high-level operations built on primitivesoperations. Such a structure is common in information systems that supporttransactions. A transaction encapsulates a set of changes to data. TheCommand pattern offers a way to model transactions. Commands have a commoninterface, letting you invoke all transactions the same way. The patternalso makes it easy to extend the system with new transactions.Participants· Command declares an interface for executing an operation.· ConcreteCommand (PasteCommand, OpenCommand)o defines a binding between a Receiver object and an action.o implements Execute by invoking the corresponding operation(s) onReceiver.· Client (Application)o creates a ConcreteCommand object and sets its receiver.· Invoker (MenuItem)o asks the command to carry out the request.· Receiver (Document, Application)o knows how to perform the operations associated with carrying outa request. Any class may serve as a Receiver.Collaborations· The client creates a ConcreteCommand object and specifies its receiver.· An Invoker object stores the ConcreteCommand object.· The invoker issues a request by calling Execute on the command. Whencommandsare undoable, ConcreteCommand stores state for undoing thecommand priorto invoking Execute.· The ConcreteCommand object invokes operations on its receiver to carryoutthe request.The following diagram shows the interactions between these objects.It illustrateshow Command decouples the invoker from the receiver(and the request it carriesout).ConsequencesThe Command pattern has the following consequences:1. Command decouples the object that invokes the operation from the onethatknows how to perform it.2. Commands are first-class objects. They can be manipulated and extendedlikeany other object.3. You can assemble commands into a composite command. An example istheMacroCommand class described earlier. In general, composite commandsarean instance of the Composite (183) pattern.4. It&apos;s easy to add new Commands, because you don&apos;t have to changeexistingclasses.ImplementationConsider the following issues when implementing the Command pattern:1. How intelligent should a command be?A command can have a wide range ofabilities. At one extreme itmerely defines a binding between a receiverand the actions that carryout the request. At the other extreme it implementseverything itselfwithout delegating to a receiver at all. The latter extremeis usefulwhen you want to define commands that are independent ofexistingclasses, when no suitable receiver exists, or when a command knowsitsreceiver implicitly. For example, a command that createsanotherapplication window may be just as capable of creating the windowasany other object. Somewhere in between these extremes are commandsthathave enough knowledge to find their receiver dynamically.2. Supporting undo and redo.Commands can support undo and redo capabilitiesif they provide a wayto reverse their execution (e.g., an Unexecute or Undooperation). AConcreteCommand class might need to store additional stateto do so. Thisstate can includeo the Receiver object, which actually carries out operationsinresponse to the request,o the arguments to the operation performed on the receiver, ando any original values in the receiver that can changeas a result ofhandling the request. The receiver must provideoperations that letthe command return the receiver to its prior state.To support one level of undo, an application needs to store only thecommandthat was executed last. For multiple-level undo and redo, theapplicationneeds a history list of commands that havebeen executed, where the maximumlength of the list determines thenumber of undo/redo levels. The historylist stores sequences ofcommands that have been executed. Traversingbackward through thelist and reverse-executing commands cancels theireffect; traversingforward and executing commands reexecutes them.An undoable command might have to be copied before it can be placed onthehistory list. That&apos;s because the command object that carried outthe originalrequest, say, from a MenuItem, will perform otherrequests at later times.Copying is required to distinguish differentinvocations of the same commandif its state can vary acrossinvocations.For example, a DeleteCommand that deletes selected objects muststoredifferent sets of objects each time it&apos;s executed. ThereforetheDeleteCommand object must be copied following execution, and the copyisplaced on the history list. If the command&apos;s state never changeson execution,then copying is not required—only a reference to thecommand need be placedon the history list. Commands that must becopied before being placed onthe history list act as prototypes (see Prototype (133)).3. Avoiding error accumulation in the undo process.Hysteresis can be a problemin ensuring a reliable,semantics-preserving undo/redo mechanism. Errorscan accumulate ascommands are executed, unexecuted, and reexecutedrepeatedly so thatan application&apos;s state eventually diverges from originalvalues. Itmay be necessary therefore to store more information in thecommand toensure that objects are restored to their original state. TheMemento (316) pattern can be applied to give the commandaccess to thisinformation without exposing the internals of otherobjects.4. Using C++ templates.For commands that (1) aren&apos;t undoable and (2) don&apos;trequire arguments,we can use C++ templates to avoid creating a Commandsubclass forevery kind of action and receiver. We show how to do this inthe SampleCode section.Known UsesPerhaps the first example of the Command pattern appears in a paper byLieberman[Lie85]. MacApp [App89] popularizedthe notion of commands for implementingundoable operations.ET++ [WGM88], InterViews [LCI+92], andUnidraw [VL90] alsodefine classes that follow theCommand pattern. InterViews defines an Actionabstract class thatprovides command functionality. It also defines anActionCallbacktemplate, parameterized by action method, that can instantiatecommandsubclasses automatically.The THINK class library [Sym93b] also uses commands to supportundoable actions.Commands in THINK are called &quot;Tasks.&quot; Taskobjects are passed along a Chain ofResponsibility (251) for consumption.Unidraw&apos;s command objects are unique in that they can behave likemessages. AUnidraw command may be sent to another object forinterpretation, and the resultof the interpration varies with thereceiving object. Moreover, the receiver maydelegate theinterpretation to another object, typically the receiver&apos;s parentin alarger structure as in a Chain of Responsibility. The receiver of aUnidrawcommand is thus computed rather than stored. Unidraw&apos;sinterpretation mechanismdepends on run-time type informationCoplien describes how to implement functors, objects thatare functions, in C++[Cop92]. He achieves a degree oftransparency in their use by overloading thefunction call operator(operator()). The Command pattern is different; its focusison maintaining a binding between a receiver and a function(i.e., action), notjust maintaining a function.
  2. Why it so difficult to find impressive strategy pattern sample in JDK code?Not defined to be highly extensible? Why it’s so easy to find dramatic strategy pattern samples in Eclipse? What about you system code? How many hats do You have?
  3. Why it so difficult to find impressive strategy pattern sample in JDK code?Not defined to be highly extensible? Why it’s so easy to find dramatic strategy pattern samples in Eclipse? What about you system code? How many hats do You have?
  4. MotivationThere are some cases when a system has to use some functionality and some cases when it doesn&apos;t. Let&apos;s say we have to implement a class that should send the results to a log file or to the console. But this is just an additional option and the data is logged depending on the configuration values. If there are cases when the client module does not have to log any data then it has to check the configuration parameter in and if block and then to call or not the Logger class. But as we know the &apos;if&apos; block is not an elegant solution.IntentProvide an object as a surrogate for the lack of an object of a given type.The Null Object Pattern provides intelligent do nothing behavior, hiding the details from its collaborators.ImplementationThe participants classes in this pattern are:AbstractClass- defines abstract primitive operations that concrete implementations have to define.RealClass - a real implementation of the AbstractClass performing some real actions.NullClass - a implementation which do nothing of the abstract class, in order to provide a non-null object to the client.Client - the client gets an implementation of the abstract class and uses it. It doesn&apos;t really care if the implementation is a null object or an real object since both of them are used in the same way.Applicability &amp; ExamplesExample: Log SystemLet&apos;s say we need a logging framework in order to support the logging of an application. The framework must fulfill the following requirements: The destination of the output messages should be selected from a configuration file and it can be one of the following options: Log File, Standard Console or Log Disabled.Must be open for extension; new logging mechanism can be added without touching the existing code.Specific problems and implementationNull Object and FactoryThe Null Object design pattern is more likely to be used in conjunction with the Factory pattern. The reason for this is obvious: A Concrete Classes need to be instantiated and then to be served to the client. The client uses the concrete class. The concrete class can be a Real Object or a Null Object. Null Object and Template MethodThe Template method design pattern need to define an abstract class that define the template and each concrete class implements the steps for the template. If there are cases when sometimes template is called and sometimes not then, in order to avoid the checking a Null Object can be use to implement a Concrete Template that does nothing.Removing old functionalityThe Null Object can be used to remove old functionality by replacing it with null objects. The big advantage is that the existing code doesn&apos;t need to be touched.ConclusionThe Null Object Pattern is used to avoid special if blocks for do nothing code, by putting the “do nothing” code in the Null Object which becomes responsible for doing nothing. The client is not aware anymore if the real object or the null object is called so the &apos;if&apos; section is removed from client implementation. ========================================================================================ConsequencesThe Null Object pattern:defines class hierarchies consisting of real objects and null objects. Null objects can be used in place of real objects when the object is expected to do nothing. Whenever client code expects a real object, it can also take a null object.makes client code simple. Clients can treat real collaborators and null collaborators uniformly. Clients normally don&apos;t know (and shouldn&apos;t care) whether they&apos;re dealing with a real or a null collaborator. This simplifies client code, because it avoids having to write testing code which handles the null collaborator specially.encapsulates the do nothing code into the null object. The do nothing code is easy to find. Its variation with the AbstractObject and RealObject classes is readily apparent. It can be efficiently coded to do nothing. It does not require variables that contain null values because those values can be hard-coded as constants or the do nothing code can avoid using those values altogether. makes the do nothing code in the null object easy to reuse. Multiple clients which all need their collaborators to do nothing will all do nothing the same way. If the do nothing behavior needs to be modified, the code can be changed in one place. Thereafter, all clients will continue to use the same do nothing behavior, which is now the modified do nothing behavior.makes the do nothing behavior difficult to distribute or mix into the real behavior of several collaborating objects. The same do nothing behavior cannot easily be added to several classes unless those classes all delegate the behavior to a class which can be a null object class.can necessitate creating a new NullObject class for every new AbstractObject class.can be difficult to implement if various clients do not agree on how the null object should do nothing as when your AbstractObject interface is not well defined.always acts as a do nothing object. The Null Object does not transform into a Real Object.ImplementationThere are several issues to consider when implementing the Null Object pattern:Null Object as Singleton. The Null Object class is often implemented as a Singleton [GHJV95, page 127]. Since a null object usually does not have any state, its state can&apos;t change, so multiple instances are identical. Rather than use multiple identical instances, the system can just use a single instance repeatedly.Clients don&apos;t agree on null behavior. If some clients expect the null object to do nothing one way and some another, multiple NullObject classes will be required. If the do nothing behavior must be customized at run time, the NullObject class will require pluggable variables so that the client can specify how the null object should do nothing (see the discussion of pluggable adaptors in the Adapter pattern [GHJV95, page 142]). This may generally be a symptom of the AbstractObject not having a well defined (semantic) interface.Transformation to Real Object. A Null Object does not transform to become a Real Object. If the object may decide to stop providing do nothing behavior and start providing real behavior, it is not a null object. It may be a real object with a do nothing mode, such as a controller which can switch in and out of read-only mode. If it is a single object which must mutate from a do nothing object to a real one, it should be implemented with the State pattern [GHJV95, page 305] or perhaps the Proxy pattern [GHJV95, page 207]. In this case a Null State may be used or the proxy may hold a Null Object.Null Object is not Proxy. The use of a null object can be similar to that of a Proxy [GHJV95, page 207], but the two patterns have different purposes. A proxy provides a level of indirection when accessing a real subject, thus controlling access to the subject. A null collaborator does not hide a real object and control access to it, it replaces the real object. A proxy may eventually mutate to start acting like a real subject. A null object will not mutate to start providing real behavior, it will always provide do nothing behavior.Null Object as special Strategy. A Null Object can be a special case of the Strategy pattern [GHJV95, page 315]. Strategy specifies several ConcreteStrategy classes as different approaches for accomplishing a task. If one of those approaches is to consistently do nothing, that ConcreteStrategy is a NullObject. For example, a Controller is a View&apos;s Strategy for handling input, and NoController is the Strategy that ignores all input.Null Object as special State. A Null Object can be a special case of the State pattern [GHJV95, page 305]. Normally, each ConcreteState has some do nothing methods because they&apos;re not appropriate for that state. In fact, a given method is often implemented to do something useful in most states but to do nothing in at least one state. If a particular ConcreteState implements most of its methods to do nothing or at least give null results, it becomes a do nothing state and as such is a null state. [Woolf96]Null Object as Visitor host. A Null Object can be used to allow a Visitor [GHJV95, page 331] to safely visit a hierarchy and handle the null situation.The Null Object class is not a mixin. Null Object is a concrete collaborator class that acts as the collaborator for a client which needs one. The null behavior is not designed to be mixed into an object that needs some do nothing behavior. It is designed for a class which delegates to a collaborator all of the behavior that may or may not be do nothing behavior. [Woolf96]