Showing posts with label object oriented programming. Show all posts
Showing posts with label object oriented programming. Show all posts

Monday, June 30, 2014

Command pattern

Command pattern: Encapsulates a request as an object, thereby letting you parametrize
other objects with different requests, queue or log requests, and support
undoable operations.
.
The command pattern allows you to decouple the requester of an action from the object actually performing the action. By introducing 'command objects' into the application design, we can encapsulate a request to do something.
command pattern uml
(command pattern)
A nice example would be programming a software for a remote. This remote should work with various devices and therefore does not know what it should do for each device. For each button we will assign a command object that knows how to communicate with the right object (receiver) that gets the work done. Using an API (application programming interface) command objects can be loaded into button slots, allowing the remote code to stay very simple.
// every class you want to use as a command object will have
// to implement this interface
public interface Command {
  public void execute();
}
Each 'command object' is bound to a specific object before it is assigned to the remote (e.g., create one LightOnCommand object for the kitchen light and one for the living room light). 
public class LightOnCommand implements Command() {
  Light light; // receiver

  public LightOnCommand(Light light) {
    this.light = light;
  }

  public void execute() {
    light.on(); // here we execute everything we want to do with the receiver object
  }
}
public class SimpleRemoteControl() { // in the UML: invoker
  Command[] commands;

  public SimpleRemoteControl() {
    commands = new Command[5];
    // it might be a good idea to initialize all commands with a NullObject
    // (an object implementing the Command interface, which does nothing -
    // this way you wont have to check if an element of commands is null)
  }

  // the command object may be changed at runtime
  public void setCommand(int slot, Command command) {
    commands[slot] = command;
  }

  // if the remote button is pressed we call the execute method of
  // our Command object
  public void buttonWasPressed(int slot) {
    commands[slot].execute();
  }
} 
The remote object does not care what command object is in its slot, as long as it implements the Command interface. The command pattern is extremely useful as the following sections will show (besides what you have already read):

Undo
With the command pattern it is very easy to implement undo actions. Simply add another method to the Command interface. When implementing this method, perform the exact opposite action/s you implemented in execute. You will also have to add a reference to the last Command that was performed (set whenever method buttonWasPressed() is called), as well as a new method undoButtonWasPushed() to our SimpleRemoteControl class.
public interface Command {
  public void execute();
  public void undo();
}
public class LightOnCommand implements Command() {
  Light light; // receiver

  public LightOnCommand(Light light) {
    this.light = light;
  }

  public void execute() {
    light.on();
  }

  public void undo() {
    light.off(); // oposite action of turning a light on
  }
}
This is easy for objects, which have only two states. If there are more states you will have to maintain a variable storing the previous state every time a new state is set. In case of an undo action you will just have to set the current state equal to the previous state.
Sometimes you want to be able to press an undo button multiple times. To implement such an undo history, instead of keeping track of just the last Command executed, you keep a stack of previous commands. Every time the undo button is pressed, you can pop a command object off the stack and execute its undo method.

Macro command
If you have a situation where several commands should be executed at once you can still use our usual command interface, but use an Array of commands for the constructor. Neat isn't it?:
public class MacroCommand implements Command() {
  Command[] commands; // command array

  public MacroCommand(Command[] commands) {
    this.commands = command;
  }

  public void execute() {
    for(int i=0; i<commands.length; ++i) {
      commands[i].execute();
    }
  }

  public void undo() {
    for(int i=0; i<commands.length; ++i) {
      commands[i].undo();
    }
  }
}

Queuing requests
The command pattern offers the possibility to package a piece of computation and pass it around as first class object. The actual computation may be invoked long after some client application creates the command object. This is very nice if you are working with multiple threads. You can use this for schedulers, thread pools, job queues, ...
Furthermore threads don't even have to be assigned for specific tasks. One time a thread may be computing a math problem, and the next time it may be sending something over the network. Using the command pattern, the job queue classes are totally decoupled form the objects that are doing the computation.

Logging requests
You may store and load command objects on disk, using java object serialization. Take a spreadsheet application for example: You might want to implement a failure recovery by logging the actions on a spreadsheet rather than writing a copy of the spreadsheet to disk every time a change occurs.

I hope this post gives you an idea of the usefulness of the command pattern. See you next time.

Tuesday, June 24, 2014

Singleton pattern

Singleton pattern: Ensures a class has only one instance, and provides
a global point of access to it.
.
There are often situations where you want an object to exist once and only once during run time of an application (e.g., for preferences, logging, thread pools, caches ...). Instantiating more than one of these objects often causes incorrect program behavior, overuse of resources or inconsistent results (due to multiple copies of objects).

The classic implementation of a singleton uses a private constructor, which is called by a static method - acting as the global point of access, preventing other classes to create new instances on their own:

public class SingletonClass{
  private static SingletonClass instance;

  private SingletonClass(){
  }

  // the static instance variable will only get instantiated once
  // after that it wont be null and therefore the private constructor
  // wont be called again
  public static SingletonClass getInstance(){
    if(instance==null){
      instance = new SingletonClass();
    }
    return instance;
  }
}

Another effect of the singleton is that the instance variable is instantiated in a lazy fashion. The object will only be created when really needed (the moment getInstance() is first called). A global variable might be created when you application begins. If an object is resource intensive and an application does not always ends up using it, using a singleton might be the better choice.

Multithreading

You have to be careful though when using multiple threads. If two threads call the getInstance() method at the same time, it may result in creating two instances of the SingletonClass. To prevent this from happening you can add synchronized to the getInstance() method:

public static syncronized SingletonClass getInstance(){
  if(instance == null){
    instance = new SingletonClass(); 
  }
  return instance;
}


Synchronized forces every thread to wait its turn before it can enter the method. No two threads may enter the method at the same time. This is expensive, particularly because the only time synchronized is relevant/needed is the first time through this method (after that instance is not null anymore).

You have three options:
  1. Use syncronized if the performance of getInstance() is not critical to your application.
  2. Use an eagerly created instance rather than an lazily created one. The JVM guarantees that the instance will be created before any thread accesses the static instance variable.
    public class SingletonClass{
      private static SingletonClass instance = new SingletonClass();
    
      private SingletonClass(){
      }
    
      public static SingletonClass getInstance(){
        return instance;
      }
    }
  3. Use double-checked locking to reduce the use of syncronization in getInstance(). We first check to see if instance is created, and if not, we syncronize. This way we only synchronize the first time, when instance is still null.
    public static SingletonClass getInstance(){    
        if(instance==null){
          synchronized (Singleton.class){ 
            if(instance==null){
              instance = new SingletonClass();
            } 
          }
        }
        return instance;
    }
You have to be careful though if you use multiple classloaders. Each classloader defines its own namespace and therefore more than one version of a class can exist, resulting in more than one instance of the singleton. By specifying the classloader yourself you can solve this issue.

Monday, June 23, 2014

Abstract Factory Pattern

Abstract Factory Pattern: Provides an interface for creating families of
related or dependent objects without specifying their concrete
classes.
.
Often the abstract factory is mistaken for a factory method. While they are both good at decoupling applications form specific implementations, it is done in different ways. Both patterns create objects, but the factory method (factory method pattern) does it through inheritance, while the abstract factory uses object composition.

To create an object using the factory method pattern, you need to extend a class and override a factory method - which will create a concrete object. The abstract factory pattern provides an abstract type for creating a family of products (groups together a set of related products). Subclasses of this type define how those products are produced. Often you can use the factory method pattern to program an abstract factory: concrete factories implement a factory method to create their products (purely to create products).


abstract factory pattern uml
(abstract factory uml)
Using our pizza store from my previous post as an example (factory method pattern), this is how it could be implemented using the abstract factory pattern:

public class AustrianPizzaStore extends PizzaStore{
  protected Pizza createPizza(String type){
    Pizza pizza = null;
    // this is our abstract factory
    PizzaIngredientFactory ingredientFactory = new AustrianPizzaIngredientFactory();
    if(type.equals("cheese")){
      // the concrete factory is passed as argument when creating a new pizza
      pizza = new CheesePizza(ingredientFactory); 
      pizza.setName("Austrian Style Cheese Pizza");
    }else if(type.equals("veggie"){
      pizza = new VeggiePizza(ingredientFactory);
      pizza.setName("Austrian Style Veggie Pizza");
    }
    return pizza;
  }
} 

public class CheesePizza extends Pizza{
  PizzaIngredientFactory ingredientFactory;

  public CheesePizza(PizzaIngredientFactory ingredientFactory){
    this.ingredientFactory = ingredientFactory;
  }

  // the abstract pizza classhas membervariables for all
  // ingredients (e.g., Cheese, Sauce, ...)
  void prepare(){
    dough = ingredientFactory.createDough();
    sauce = ingredientFactory.createSauce();
    cheese = ingredientFactory.createCheese();
  }
}

public class AustrianPizzaIngredientFactory implements PizzaIngredientFactory {
  public Dough createDough(){
    return new ThinCrustDough();
  }
  public Sauce createSauce(){
    return new TomatoSauce();
  }
  public Cheese createCheese(){
    return new GudaCheese();
  }
  // this class has to implement every method defined in the 
  // PizzaIngredientFactory interface (Veggies, Pepperoni, Clams ...)
}
As you can see, to use the factory, one subclass is instantiated and passed into some code (AustrianPizzaFactory, CheesePizza) that is written against the abstract type. A disadvantage is that if a set of related products is extended (e.g., adding another ingredient) the whole interface has to change, which means that you have to change the interface of every subclass ... lots of work.

But the PizzaIngredientFactory allows us to handle groups of different ingredient objects. As you can imagine Austria will use different ingredients than lets say Russia or America for their cheese pizzas due to different local availability of those ingredients, or regional preferences of the population. Even though our pizza stores are using the same brand name, Austrian stores might have to use thin crust dough, gouda cheese and frozen fish, while American stores can use thick crust dough, mozzarella cheese and fresh fish.

So keep in mind to use the abstract factory whenever you have families of products that you need to create and you want to make sure that your clients create products that belong together. Use factory methods to decouple client code form concrete classes you need to instantiate, or if you don't know ahead of time which concrete classes you are going to need.

Friday, June 20, 2014

Factory Pattern


Factory Pattern: Attaches additional responsibilities to an object dynamically and 
provide a flexible alternative to subclassing for extending
functionality.
.
Often when you have a set of related classes you are forced to write code like this:
Animal animal;
if(wood){
  animal = new Bear();
}else if(sea){
  animal = new Fish();
}else if(home){
  animal = new Dog();
}
With code like this, you know that later on, when things have to be changed or extended you will have to reopen this code and check what has to be added or deleted. If this code ends up in several parts of your application maintenance and updates become cumbersome and error-prone. This can be solved using Factories - handling the details of object creation. Any time another class needs e.g. an animal, it asks the animal factory to create one.

Simple Factory & Static Factory
Encapsulating this object creation process in its own class we get a simple factory. We now have only one place to where we can implement changes. If you define this simple factory as static you get a static factory - advantage: no need to instantiate an object - disadvantage: can't subclass and change behavior.
public class SimpleAnimalFactory{
   public Animal createAnimal(String type){
    Animal animal;
    if(type.equals("wood")){
      animal = new Bear();
    }else if(type.equals("sea")){
      animal = new Fish();
    }else if(type.equals("home")){
      animal = new Dog();
    }
    return animal;
  }
}
This simple factory isn't an actual design pattern (more like an idiom) - still it is commonly used. Simple factories do not give you control over what should happen after an object was instantiated. The next two real factory patterns give you a little bit more 'quality control'.


Factory Method Pattern: A factory mehtod handles object creation and encapsulates it in 
a subclass. This decouples the client code in the superclass 
from the object creation code in the subclass.

The factory method pattern lets subclasses decide which objects should be created, but specyfies other processes which should stay the same among all subclasses. Imagine a pizza franchise where each pizza shop can decide for a regional pizza style. Still the order system should stay the same for each shop.
public abstract class PizzaStore{
  public Pizza orderPizza(String type){
    Pizza pizza = createPizza(type);
    pizza.prepare();
    pizza.bake();
    pizza.cut();
    pizza.box();
    return pizza;
  }

  abstract Pizza createPizza(String type);
}
Now each pizza shop may implement its own createPizza method, e.g., the Austrian pizza shop creates AustrianStyleCheesePizza, while the American pizza shop creates AmericanSyleCheesePizza.
if(type.equals("cheese")){
  animal = new AustrianStyleCheesePizza();
}
if(type.equals("cheese")){
  animal = new AmericanStyleCheesePizza();
}
The abstract class PizzaStore does a lot of things with a Pizza object, but because Pizza is abstract it has no idea what real concrete classes are involved - it is decoupled. With this simple transformations we have gone from having an object handling the instantiation of concrete classes (simple factory) to a set of subclasses that take on that responsibility.

The factory method pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.

factory method pattern uml
(factory method uml)
Advantages:
  • By placing all creation code in one object or method, code duplication is avoided and you provide one place to perform maintenance. 
  • Clients depend only upon interfaces rather than concrete classes required to instantiate objects (programming to an interface - more flexible, extensible).
The factory method pattern makes use of the dependency inversion principle (Check out all other design principles in this post OO principles):

Design Principle 6: Depend upon abstractions. Do not depend upon concrete classes. It suggests that our high-level components (PizzaStore) should not dpend on our low-level components (ConcretePizza).

In our factory method pattern example both the high-level component PizzaStore and the low-level components concrete pizzas depend on Pizza, the abstraction.


Next post: Abstract Factory Pattern


Tuesday, June 3, 2014

Design Patterns in Programming


In software development there is one constant:
CHANGE

All applications will grow and change over time, or die. As a developer it is therefore desirable for an application to be easy to understand, maintainable and flexible. You may think that knowing the object oriented basics will automatically result in such applications, but:
  • Knowing OO basics does not make you a good OO designer.
  • Good OO designs are reusable, extensible and maintainable.
  • Patterns show you how to build systems with good OO design qualities.
  • Patterns are proven OO experience.
  • Patterns don't give you code, they give you general solutions to design problems. You apply them to your secific application.
  • Patterns are not invented but discovered.
  • Most patterns and principles adress issues of change in software
  • Most patterns allow some part of a system to vary independently of all other parts.
Design patterns are not just good object-oriented design. Knowing OO basics does not mean you will automatically be good at building flexible, reusable, and maintainable systems. They are a collection of, sometimes non-obvious, ways of constructing OO systems (let you skip the hard work of finding those ways yourself). If you can not find a pattern that matches your problem, think about the Design principles that design patterns use.

Advantage of design patterns:
  1. shared vocabulary with other developers (less time explaining).
  2. do not just communicate a pattern name, but also a whole set of qualities, characteristics and constraints that the pattern represents. e.g.: Strategy Pattern encapsulated behavior into its own set of classes that can be easily expanded and changed at run time
  3. Allows to keep discussions at the design level (not too much details of implementation) better structure of applications (easy to understand, maintainable, flexible)
In the next few posts I want to cover the following topics:

OO Basics:
    Abstraction
    Encapsulation
    Polymorphism
    Inheritance
OO Principles
OO Patterns
    Strategy
    Observer
    Decorator
    Factory Method
    Abstract Factory
    Singleton
    Command 

(I will be editing this page, adding other patterns)