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 17, 2014

Decorator Pattern

Decorator Pattern: Attaches additional responsibilities to an object dynamically and 
provide a flexible alternative to subclassing for extending
functionality.

Since programming schemes using inheritance often result in class explosion, rigid design or adding functionality to the base class that is not appropriate for other subclasses, another design pattern may be used - the decorator pattern. This pattern follows the open-closed principle (Check out all other design principles in this post: OO principles):

Design Principle 5: Classes should be closed to change, but open to extensions. This allows to incorporate new behavior without changing existing code. This principles seems like a contradiction, but there are techniques for allowing code to be extended without direct modification.
Still be careful when choosing the areas of code that need to be extended. Applying the open-closed principle everywhere is wasteful, unnecessary, and can lead to complex, hard to understand code.

Example: Imagine a pizza shop having different types of dough and various toppings (cheese, salami, ham, ...). The pizza shop wants to be able to combine its different types of dough with all their toppings (dynamically).
The decorator pattern uses 'decorator' objects to decorate/wrap another object. This is possible since these 'decorator' objects have the same supertype as the objects they decorate. The decorator adds its own behavior either before and/or after delegating to the object it decorates to do the rest of the job.  
To implement the decorator pattern for our pizza shop, the different types of dough serve as our concrete components, while available toppings serve as our decorators. Each decorator holds (wraps/has-a) component, an instance variable that holds a reference to a component.
Decorator uml (wikipedia)
We are therefore able to decorate our doughs dynamically at run time with as many toppings as we like. By using a combination of inheritance (subclassing) and composition this pattern gains a lot more flexibility at run time. Decorators are meant to add behavior to an object they wrap.

The decorator pattern is often used in combination with other patterns, like Factory and Builder. This way the creation of concrete components with its decorators is 'well encapsulated' and does not lead to problems like increased chance of coding errors due to adding a lot of small classes, occasionally resulting in a less straightforward design (for other developers to understand)


Thursday, June 5, 2014

Observer Pattern

Observer Pattern: Defines a one to many relationship between a set of objects. When the state of one object (subject) changes, all others (Observers) are notified.

Use this pattern, if you have objects that have to be updated if data in another object changes. For the observer pattern you will have to use at least two interface classes. One for the subject and one for the observer classes.
 interface Observer{
     update();  // called by a subject
 }.
 interface Subject{
     registerObserver(Observer observer);
     deregisterObserver(Observer observer);
     notifyAll();  // iterates over a list of registered observers calling their 
                   // update method
 }
A class which implements the Subject interface has to maintain a list of observers (e.g., List<Observer>). The methods registerObserver and deregisterObserver are used to to add/remove objects implementing the observer interface. Like the Strategy Pattern from my last post, the observer pattern also uses following design principles:
  1. Identify aspects of an application that vary and separate them form what stays the same.
  2. Program to an interface, not an implementation. Exploit polymorphism by programming to a supertype.
  3. Favor composition (has-a relationships) over inheritance. 
Check out OO principles for detailed explanations of each design principle. In addition the following new one is utilized:

Design Principle 4: Strive for loosely coupled designs between objects that interact. Such objects can interact, but have very little knowledge of each other. This allows for flexible OO systems that can handle change because they minimize the interdependency between objects.

Observer uml (wikipedia)

Results:
  • The only thing that is known to the subject is that the observer implements the observer interface. (Does not need to know the actual class of the observer object)
  • The subject can add new observers at any time.
  • You will never need to modify the subject to add new types of observers.
  • You can reuse subjects or observers independently of each other.
  • Changes to either the subject or an observer will not affect the other.
Observers can work either by pushing or pulling data. void update(Subject sub, Object arg)    Never depend on order of evaluation of the Observer notifications.

Wednesday, June 4, 2014

OO Principles

These are all principles for object oriented programming in one post (will be regularly updated along with the design patterns that use them):

  1. Identify aspects of an application that vary and separate them form what stays the same. Later you will be able to alter or extend the parts that vary without affecting other parts, resulting in fewer unintended consequences from code changes and more flexibility in a system - Encapsulate. E.g.: use separate classes to delegate behavior - instanced by the class using those behaviors. This way it is also easy to change behavior on run time (getter, setter).

     class Dog(){  
         // (FightBehavior is an interface - multiple Behavior  
         // patterns may be implemented) same goes for PlayBehavior  
         FightBehavior fBehavior;  
         PlayBehavior pBehavior;  
         void fight();  
         void play();  
     }  
    

  2. Program to an interface, not an implementation. Exploit polymorphism by programming to a supertype. e.g.: do not use:
    Dog d = new Dog();
    d.bark();
    instead use:
    interface Animal();   // having a method makeNoise 
    Dog d = new Animal(); // Dog implements Animal
    d.makeNoise();

  3. Favor composition (has-a relationships) over inheritance.
  4. Strive for loosely coupled designs between objects that interact. Such objects can interact, but have very little knowledge of each other. This allows for flexible OO systems that can handle change because they minimize the interdependency between objects.
  5. Classes should be closed to change, yet open to extensions. Thereby it is easy to incorporate new behavior without modifying existing code (correct, tested, bug free code should stay unaltered - lowering chances of introducing new bugs or unintended side effects) - Open-Closed principle. 
  6. Depend upon abstractions. Do not depend upon concrete classes. It suggests that high-level components (like an abstract class PizzaStore) should not dpend on low-level components (ConcretePizza) - Dependency Inversion Principle

Strategy Pattern

Strategy Pattern: Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Allows for reuse of code through inheritance and composition
 
Use this pattern if you have to develop an application, that may change over time (it will change) or when features that are not known yet, should be added. The strategy pattern uses a number of design principles. I will try to explain each principle with an example.

Design Principle 1: Identify aspects of an application that vary and separate them form what stays the same. Encapsulate: Later you will be able to alter or extend the parts that vary without affecting other parts. Result: Fewer unintended consequences from code changes and more flexibility in a system. E.g.: use separate classes to delegate behavior - instanced by the class using those behaviors. This way it is also easy to change behavior on run time (getter, setter).

 class Dog(){  
     // (FightBehavior is an interface - multiple Behavior  
     // patterns may be implemented) same goes for PlayBehavior  
     FightBehavior fBehavior;  
     PlayBehavior pBehavior;  
     void fight();  
     void play();  
 }  

Design Principle 2: Program to an interface, not an implementation. Exploit polymorphism by programming to a supertype.
e.g.: not Dog d = new Dog();
      d.bark();
      use Dog d = new Animal();
      d.makeNoise();

Design Principle 3: Favor composition (has-a relationships) over inheritance.
  • has-a:  each dog has a fight behavior to which it delegates fighting (behavior is being composed with the right behavior object
  • is-a: inheriting behavior from other classes
Strategy uml
 Remember: More time is spent on code after development is complete (maintaining and changing software).

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)