memento pattern

MEMENTO DESIGN PATTERN

The word ‘memento’ refers to an object kept as a reminder or souvenir of a person or event. Memento pattern is a behavioral pattern in GoF because it captures and externalize an object’s internal state so that the object can be restored to this state at a later time.

source: GoF

OVERVIEW

Memento, the class that represents a snapshot, simply contains the state of an object to be restored to an Originator. You and get and set state that a Memento encapsulates inside.

Originator, the class in which the current state is held. Originator has a member function that creates and return a Memento with the current state of the Originator stored into the Memento. Originator also has a member function that sets its current state with the state of a given Memento object. In other words, it can create snapshot (Memento), or restore the state to the given snapshot (Memento).

Caretaker object keeps and holds the Mementos, but never modify the Mementos. Caretaker class is responsible for the memento’s safekeeping. Usually, Caretaker encapsulates a list of Mementos that you can add more to the list, or get a Memento from the list.

MEMENTO CODE EXAMPLE

Memento class:

public class Memento {
private String state;

public Memento(String state){
this.state = state;
}

public String getState(){
return state;
}
}

Originator class:

public class Originator {
private String state;

public void setState(String state){
this.state = state;
}

public String getState(){
return state;
}

public Memento createMemento(){           // return a current snapshot
return new Memento(state);
}

public void setMemento(Memento Memento){  // restore from a snapshot
state = Memento.getState();
}
}

Caretaker class:

public class Caretaker {
private List<Memento> mementoList = new ArrayList<Memento>();

public void add(Memento state){
mementoList.add(state);
}

public Memento get(int index){
return mementoList.get(index);
}
}

main():

public class MementoPatternDemo {
public static void main(String[] args) {

Originator originator = new Originator();
Caretaker caretaker = new Caretaker();

originator.setState(“State #1”);
originator.setState(“State #2”);
caretaker.add(originator.createMemento());

originator.setState(“State #3”);
caretaker.add(originator.createMemento());

originator.setState(“State #4”);
System.out.println(“Current State: ” + originator.getState());

originator.setState(caretaker.get(0));
System.out.println(“First saved State: ” + originator.getState());
originator.setState(caretaker.get(1));
System.out.println(“Second saved State: ” + originator.getState());
}
}

Output:

Current State: State #4
First saved State: State #2
Second saved State: State #3

WHEN TO USE MEMENTO

  • Need an undo and restore mechanism.
  • Database rollback. To be able to rollback, have the Originator create a snapshot (memento) before performing an operation and thus in case of failure, the memento object would be used to restore the Originator to its previous state.
  • Want to simplify Originator code so it does not need to keep track of its previous state by moving such responsibility to the Caretaker code.

COMPARISON

memento vs command

  • Both can act as magic tokens to be passed around and invoked at a later time.
  • ​In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time.
  • Both can support muti-level undos.
  • Memento pattern’s capturing and restoring object state is more expensive then Command patterns for Undo/Redo functionality.

singleton design pattern

Singleton design pattern

Motivation

Sometimes it’s important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.

The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Intent

  • Ensure that only one instance of a class is created.
  • Provide a global point of access to the object.

Implementation

The implementation involves a static member in the “Singleton” class, a private constructor and a static public method that returns a reference to the static member.

Singleton Implementation - UML Class Diagram

The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients. getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.

class Singleton
{
	private static Singleton instance;
	private Singleton()
	{
		...
	}

	public static synchronized Singleton getInstance()
	{
		if (instance == null)
			instance = new Singleton();

		return instance;
	}
	...
	public void doSomething()
	{
		...	
	}
}

You can notice in the above code that getInstance method ensures that only one instance of the class is created. The constructor should not be accessible from the outside of the class to ensure the only way of instantiating the class would be only through the getInstance method.

The getInstance method is used also to provide a global point of access to the object and it can be used in the following manner:

Singleton.getInstance().doSomething();

Applicability & Examples

According to the definition the singleton pattern should be used when there must be exactly one instance of a class, and when it must be accessible to clients from a global access point. Here are some real situations where the singleton is used:

Example 1 – Logger Classes

The Singleton pattern is used in the design of logger classes. This classes are usually implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

Example 2 – Configuration Classes

The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.

Example 3 – Accessing resources in shared mode

It can be used in the design of an application that needs to work with the serial port. Let’s say that there are many classes in the application, working in an multi-threading environment, which needs to operate actions on the serial port. In this case a singleton with synchronized methods could be used to be used to manage all the operations on the serial port.

Example 4 – Factories implemented as Singletons

Let’s assume that we design an application with a factory to generate new objects(Acount, Customer, Site, Address objects) with their ids, in an multi threading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstract Factory or Factory Method and Singleton design patterns is a common practice.

Specific problems and implementation

Thread-safe implementation for multi-threading use.

A robust singleton implementation should work in any conditions. This is why we need to ensure it works when multiple threads uses it. As seen in the previous examples singletons can be used specifically in multi-threaded application to make sure the reads/writes are synchronized.

Early instantiation using implementation with static field

In the following implementattion the singleton object is instantiated when the class is loaded and not when it is first used, due to the fact that the instance member is declared static. This is why in we don’t need to synchronize any portion of the code in this case. The class is loaded once this guarantee the uniquity of the object.

Singleton – A simple example (java)

//Early instantiation using implementation with static field.
class Singleton
{
	private static Singleton instance = new Singleton();

	private Singleton()
	{
		System.out.println("Singleton(): Initializing Instance");
	}

	public static Singleton getInstance()
	{    
		return instance;
	}

	public void doSomething()
	{
		System.out.println("doSomething(): Singleton does something!");
	}
}

Protected constructor

It is possible to use a protected constructor to in order to permit the subclassing of the singeton. This techique has 2 drawbacks that makes singleton inheritance impractical:

  • First of all, if the constructor is protected, it means that the class can be instantiated by calling the constructor from another class in the same package. A possible solution to avoid it is to create a separate package for the singleton.
  • Second of all, in order to use the derived class all the getInstance calls should be changed in the existing code from Singleton.getInstance() to NewSingleton.getInstance().

Multiple singleton instances if classes loaded by different classloaders access a singleton.

If a class(same name, same package) is loaded by 2 diferent classloaders they represents 2 different clasess in memory.

Abstract Factory and Factory Methods implemented as singletons.

There are certain situations when the a factory should be unique. Having 2 factories might have undesired effects when objects are created. To ensure that a factory is unique it should be implemented as a singleton. By doing so we also avoid to instantiate the class before using it.

Hot Spot:

  • Multithreading – A special care should be taken when singleton has to be used in a multithreading application.
  • Serialization – When Singletons are implementing Serializable interface they have to implement readResolve method in order to avoid having 2 different objects.
  • Classloaders – If the Singleton class is loaded by 2 different class loaders we’ll have 2 different classes, one for each class loader.
  • Global Access Point represented by the class name – The singleton instance is obtained using the class name. At the first view this is an easy way to access it, but it is not very flexible. If we need to replace the Sigleton class, all the references in the code should be changed accordinglly.

Software design pattern

What is Software design pattern?

in Software industry it’s myth what is Software design pattern? and how to know which one is suitable for what module. can we create my own design pattern? to overcome this myth i had go through few article and tried to collect at one place, so let’s start.

Myth 1:- For a good architecture all design patterns have to be implemented in a project.

Fact: – Patterns come out naturally and is completely on-demand.

“Time tested Solution for recurring architecture problems”.

But frankly this definition will not hold true as you start implementing and reading design pattern. At one moment of time you will see design pattern is all about good OOP ( Object oriented programming) principles.

So let me put my definition as per my understanding and experience. I can guarantee that when we start running through all design patterns this definition would be more clear.

“Time tested Solution for recurring OOP problems”.

Categories of software design pattern 

Design patterns were originally grouped into the categories: creational patterns, structural patterns, and behavioral patterns, and described using the concepts of delegation, aggregation, and consultation. For further background on object-oriented design, see coupling and cohesion, inheritance, interface, and polymorphism. Another classification has also introduced the notion of architectural design pattern that may be applied at the architecture level of the software such as the Model–View–Controller pattern.

Creational patterns

Creational patterns further categorized into subcategories:

Singleton
Ensure a class has only one instance, and provide a global point of access to it.
When to use:
Singleton pattern should be used when we must ensure that only one instance of a class is created and when the instance must be available through all the code. A special care should be taken in multi-threading environments when multiple threads must access the same resources through the same singleton object.
Abstract factory
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

When to use:

  • A system should be configured with one of multiple families of products
  • A system should be independent of how its products are created, composed and represented
  • Products from the same family should be used all together, products from different families should not be used togheter and this constraint must be ensured.
  • Only the product interfaces are revealed, the implementations remains hidden to the clients.

Builder
Separate the construction of a complex object from its representation, allowing the same construction process to create various representations.

Factory method
Define an interface for creating a single object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses (dependency injection).

Lazy initialization

Tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. This pattern appears in the GoF catalog as “virtual proxy”, an implementation strategy for the Proxy pattern.
When to use:
Basically, we’ll use an object pool whenever there are several clients who needs the same stateless resource which is expensive to create. like Database Connections, Remote Objects

Prototype
Specify the kinds of objects to create using a prototypical instance, and create new objects from the ‘skeleton’ of an existing object, thus boosting performance and keeping memory footprints to a minimum.

Structural patterns

Structural patterns further categorized into subcategories:

Adapter
Convert the interface of a class into another interface clients expect. An adapter lets classes work together that could not otherwise because of incompatible interfaces. The enterprise integration pattern equivalent is the translator.

Bridge
Decouple an abstraction from its implementation allowing the two to vary independently.

Proxy
Provide a surrogate or placeholder for another object to control access to it.

Facade
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Flyweight
Use sharing to support large numbers of similar objects efficiently.

Behavioral Design Patterns

Behavioral Design Patterns further categorized into subcategories:

Chain of Responsibly
It avoids attaching the sender of a request to its receiver, giving this way other objects the possibility of handling the request too.
The objects become parts of a chain and the request is sent from one object to another across the chain until one of the objects will handle it.

Command
Encapsulate a request in an object, Allows the parameterization of clients with different requests and Allows saving the requests in a queue.

Memento
Without violating encapsulation, capture and externalize an object’s internal state allowing the object to be restored to this state later.

Interpreter

Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language / Map a domain to a language, the language to a grammar, and the grammar to a hierarchical object-oriented design.

Iterator
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Mediator
Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

Observer
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Template Method
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses / Template Method lets subclasses redefine certain steps of an algorithm without letting them to change the algorithm’s structure.

Visitor
Represents an operation to be performed on the elements of an object structure / Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Null Object
Provide 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.