Since these presentations were spare time hobby - I've decided to share them :)
Hopefully someone will find them useful.
This part continues 1. part with more design patterns like Command, State, NullObject.
JavaScript language plays a very important role in Web 2.0 application development. JavaScript has its own characteristics different than object-oriented languages and it's not easy for developers to understand.
This presentation covers major advanced topics in JavaScript languages, including prototype chain, identifier resolving, "this" keyword, "new" operator, execution context and scope chain and closure. Besides that, it also covers best practices when using JavaScript.
JavaScript has some stunning features like Closures, Prototype etc. which can help to improve the readability and maintainability of the code. However, it is not easy for inexperienced developer to consume and apply those features in day to day coding. The purpose of the presentation ‘Advanced JavaScript’ is to help a reader easily understand the concept and implementation of some advanced JavaScript features.
JavaScript language plays a very important role in Web 2.0 application development. JavaScript has its own characteristics different than object-oriented languages and it's not easy for developers to understand.
This presentation covers major advanced topics in JavaScript languages, including prototype chain, identifier resolving, "this" keyword, "new" operator, execution context and scope chain and closure. Besides that, it also covers best practices when using JavaScript.
JavaScript has some stunning features like Closures, Prototype etc. which can help to improve the readability and maintainability of the code. However, it is not easy for inexperienced developer to consume and apply those features in day to day coding. The purpose of the presentation ‘Advanced JavaScript’ is to help a reader easily understand the concept and implementation of some advanced JavaScript features.
This is Class 2 on a 6 week course I taught on Software Design Patterns.
This course discusses Strategy and Template pattern.
Class based on "Head First Design Patterns."
There are several JavaScript libraries available in the world of web programming. And, as the usage and complexity is increasing day by day, sometimes it becomes very difficult and confusing to understand and create modules using those libraries, especially for those having strong background of Object Oriented Languages.
So this one hour session will make an effort to go into the very basics of JavaScript and put a base for writing modular JavaScript code.
How can you get more done by doing less? Can Spring Web MVC applications look simpler? How can writing less code mean more? How can using Groovy in JUnit tests speed up writing tests. Making data driven tests cool with Spock. All in existing living Java web applications with sample code in Java and Groovy.
introduction, The Resolution of Property Names on Objects.
Closure
A "closure" is an expression (typically a function) that can have
free variables together with an environment that binds those
variables (that "closes" the expression)
This is Class 2 on a 6 week course I taught on Software Design Patterns.
This course discusses Strategy and Template pattern.
Class based on "Head First Design Patterns."
There are several JavaScript libraries available in the world of web programming. And, as the usage and complexity is increasing day by day, sometimes it becomes very difficult and confusing to understand and create modules using those libraries, especially for those having strong background of Object Oriented Languages.
So this one hour session will make an effort to go into the very basics of JavaScript and put a base for writing modular JavaScript code.
How can you get more done by doing less? Can Spring Web MVC applications look simpler? How can writing less code mean more? How can using Groovy in JUnit tests speed up writing tests. Making data driven tests cool with Spock. All in existing living Java web applications with sample code in Java and Groovy.
introduction, The Resolution of Property Names on Objects.
Closure
A "closure" is an expression (typically a function) that can have
free variables together with an environment that binds those
variables (that "closes" the expression)
Object-Oriented Programming has well established design principles, such as SOLID. For many developers architecture and functional programming are at odds with each other: they don’t know how their existing tricks of the trade convert into functional design. This problem becomes worse as hybrid languages such as Scala, Java 8 and Ruby become common. I will talk about how functional programming helps you implement the SOLID principles, and how a functional mindset can actually help you achieve the holy grail of OO, encapsulation.
10 Typical Problems in Enterprise Java ApplicationsEberhard Wolff
This presentation shows some typical problems that you will find in far too many Enterprise Java Applications. It is the result of quite a few code reviews I did as a consultant.
Esta charla comprende las lecciones aprendidas convirtiendo la app de Android de Teambox (una app repleta de deuda técnica y con un alto nivel de acoplamiento entre clases), en la versión actual de Redbooth, que intenta cumplir la arquitectura Hexagonal y los principios SOLID. Durante la exposición explicaremos como fuimos desenredando el código paso a paso; como aplicamos por partes los conceptos de la arquitectura hexagonal; como dejamos de lado componentes del framework de Android que dificultaban el mantenimiento de la app; y que errores cometimos, como los solucionamos y como se podrían haber evitado.
react-slides.pdf gives information about react libraryjanet736113
React is a framework that employs Webpack to automatically compile React, JSX, and ES6 code while handling CSS file prefixes. React is a JavaScript-based UI development library. Although React is a library rather than a language, it is widely used in web development. The library first appeared in May 2013 and is now one of the most commonly used frontend libraries for web development.
React offers various extensions for entire application architectural support, such as Flux and React Native, beyond mere UI,When compared to other technologies on the market, React is a new technology. Jordan Walke, a software engineer at Facebook, founded the library in 2011, giving it life. The likes of XHP, a straightforward HTML component framework for PHP, have an influence on React. React's newsfeed was its debut application in 2011. Later, Instagram picks it up and incorporates it into their platform,
Advantages
Makes use of the JavaScript structure known as virtual DOM. Since JavaScript's virtual DOM is quicker than the conventional DOM, this will boost the speed of programs.
Can be used with various systems and on both client and server sides is commendable.
Components and identify trends make larger apps easier to manage by increasing clarity.
Limitations
Only addresses the app's angle and distance; as a result, additional techniques must be selected if you want a full collection of development tools.
Employs inline scripting and JSX, which some programmers might find uncomfortable.
Adding a modern twist to legacy web applicationsJeff Durta
Avoid misery of working with legacy code
We will see how you can add independent and isolated components to existing pages; pages that may be difficult to change
React and Flux allow you to make self-contained additions that handle their own data access/persistence
Developing enterprise applications today using JavaFX is a challenge. The industry has not matured enough to identify patterns and practices. Consequently practioners (architects and developers alike) commit the same mistakes again and again. There is a complete lack of non-UI frameworks that make JavaFX application development easy and fast. FxObjects attempts to address that gap. The 0.1 version released provides powerful features.
Adding a modern twist to legacy web applicationsJeff Durta
Avoid misery of working with legacy code
We will see how you can add independent and isolated components to existing pages; pages that may be difficult to change
React and Flux allow you to make self-contained additions that handle their own data access/persistence
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); } }
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
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
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.)
MotivationSometimes it'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'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'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's receiver is the Document object it issupplied upon instantiation.The Execute operation invokes Paste onthe receiving Document.OpenCommand'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'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'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'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'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's easy to add new Commands, because you don'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'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's executed. ThereforetheDeleteCommand object must be copied following execution, and the copyisplaced on the history list. If the command'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'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't undoable and (2) don'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 "Tasks." Taskobjects are passed along a Chain ofResponsibility (251) for consumption.Unidraw'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's parentin alarger structure as in a Chain of Responsibility. The receiver of aUnidrawcommand is thus computed rather than stored. Unidraw'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.
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?
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?
MotivationThere are some cases when a system has to use some functionality and some cases when it doesn't. Let'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 'if' 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'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 & ExamplesExample: Log SystemLet'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'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 'if' 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't know (and shouldn't care) whether they'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't change, so multiple instances are identical. Rather than use multiple identical instances, the system can just use a single instance repeatedly.Clients don'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'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'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]