Showing posts with label Technical Architecture. Show all posts
Showing posts with label Technical Architecture. Show all posts

Friday, February 24, 2012

More Patterns-2

The Decorator Pattern attaches additional responsibilities to an object dynamically. It provides a flexible alternative to subclassing for extending functionality.
Decorators (java.io is a good example):
  • Have same supertype as the objects they decorate
  • You can use one or more decorators to wrap an object
  • Objects can be decorated at runtime
  • The decorator adds its own behaviour either before and/or after delegating to the object it decorates to do the rest of the job
  • Can make code complex and cause problems if not well-thought, need to be careful before using it
Decorator pattern = responsibility. New responsibilities or behaviours are added to the design, without altering existing code.

The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which classes to instantiate. Factory Method lets a class defer instantiation to subclasses.

Factory employs two parallel class hierarchies: the creator classes and the product classes. The pattern isolates object creation and reduces object dependency.

he Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.

The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.

To prevent problems with multi-threading in Singleton creation, you can:
  • Synchronise the getInstance method. This is expensive, but is easy and can be done if we don’t expect it to be called many times
  • Use eager instantiation of the instance, if that is not too expensive and we expect Singleton to be definitely used early on
  • Use “double-check locking”. Can be done only in Java 5 and greater and can be an overkill
public class Singleton {
    private volatile static Singleton uniqueInstance;
    private Singeton() { }
    public static Singleton getInstance(){
        if(uniqueInstance==null){
            synchronized(Singleton.class){
                if(uniqueInstance==null){
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}

The Command Pattern encapsulates the request as an object, thereby letting you parameterise other objects with different requests, queue or log requests, and support undoable operations.
Think of command as a waiter carrying requests from customer to chef for execution. Command itself does less work, with most of the work offloaded to an encapsulated class.
public interface Command {
 public void execute();
}


Monday, February 13, 2012

More on Patterns - 1

Useful reminders for some useful patterns:

The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

The Template Method Pattern ensures that the algorithm lives in only one place.

A hook is a method declared in the abstract class containing the template, but given an empty or default implementation. It can be used to help the subclasses to conditionally control the flow of the algorithm, or implement/skip an optional part of the algorithm.

A lot of people use this pattern, especially for making frameworks.

Factory Method is specialisation of Template Method

Strategy and Template Method Patterns both encapsulate algorithms, one by inheritance and one by composition

The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and composition of objects uniformly.

Composite Pattern often used in UI design.

If the composite structure is complex or expensive to traverse, it may help to use caching.

There are trade-offs in implementing Composite: need to balance transparency and safety with your needs.

The State Pattern allows an object to alter its behaviour when its internal state changes. The object will appear to change its class.

Strategy and State look very similar, but differ by intent. Think of Strategy Pattern as a flexible alternative to subclassing. You change the behaviour by composing with a different object. Think of State Pattern as an alternative to putting a lot of conditionals in your context. You can simply change the state object in the context to change its behaviour.

The Proxy Pattern provides a surrogate or placeholder for another object to control access to it.

Remote Proxy controls access to remote objects (RMI), Virtual Proxy controls access to resources expensive to create (loading messages), and Protection Proxy controls access to resources based on access rights (Java dynamic proxy).

Thursday, December 15, 2011

Basic Patterns Catalogue

Summarising key patterns used in development for reference.

A Pattern is a solution to a problem in a context.

An Anti-Pattern tells you how to go from problem to a bad situation.

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

The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

Use Bridge Pattern to vary not only your implementation, but also your abstraction.

Use Builder Pattern to encapsulate the construction of a product and allow it to be constructed in steps. It encapsulates the way a complex object is created.

Use Chain of Responsibility Pattern when you want to give more than one object a chance to handle a request.

The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and composition of objects uniformly.

The Command Pattern encapsulates the request as an object, thereby letting you parameterise other objects with different requests, queue or log requests, and support undoable operations.

The Decorator Pattern attaches additional responsibilities to an object dynamically. It provides a flexible alternative to subclassing for extending functionality.

The Facade Pattern provides a unified interface to a set of interfaces in a subsystem. It defines a higher level interface that makes the subsystem easier to use.

The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which classes to instantiate. Factory Method lets a class defer instantiation to subclasses.

Use the Flyweight Pattern when one instance of a class can be used to provide many “virtual instances”.

Use Interpreter Pattern to build an interpreter for a simple language.

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

Use the Mediator Pattern to centralise complex communications and controls between related objects. It can become overly complex without proper design.

Use the Memento Pattern when you need to be able to return an object to one of its previous states, e.g. if your user requests an “undo”.

Use the Prototype Pattern when creating an instance of a given class is either expensive or complicated.

The Proxy Pattern provides a surrogate or placeholder for another object to control access to it.

The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.

The State Pattern allows an object to alter its behaviour when its internal state changes. The object will appear to change its class.

The 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.

The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

Use the Visitor Pattern when you want to add capabilities to a composite of objects and encapsulation is not important.

Please refer http://c2.com/ppr/ for more on patterns.

Tuesday, November 29, 2011

10 Design Principles

Was going through my older notes, brushing up some technical bits. My first book for design patterns was the original book by the Gang of Four. However, the book that helped me understand Design Patterns the best was Head First Design Patterns. Following are the key design principles summarised in the book:
  1. Identify the aspects of the application that vary and separate them from what stays the same: use encapsulation.
  2. Program to an interface, not an implementation
  3. Favour composition over inheritance
  4. Strive for loosely coupled designs between objects that interact
  5. While inheritance is powerful, it does not always lead to the most flexible or maintainable designs
  6. Code should be closed to change but open to extension
  7. Principle of least knowledge: talk only to your immediate friends. Only invoke methods that belong to:
    • The object itself
    • Objects passed in a parameter to the method
    • Any object that the method creates or instantiates
    • Any components of the object
  8. Depend upon abstractions. Do not depend upon concrete classes
    • Avoid variables that hold reference to a concrete class (use Factory)
    • Avoid deriving class from concrete classes
    • Avoid overriding any of the implemented methods of a base class
    • You can ignore these guidelines if the class is highly unlikely to change
  9. Hollywood principle: don’t call us, we’ll call you. Low level components can hook into the system, but high level components determine when they are needed.
  10. A class should have only one reason to change
I have put this blog for my own reference, but hope it helps somebody else as well. To learn more, you will have to refer Head First. In next few posts I will summarise key design patterns as described in the book.