Wednesday, October 10, 2012

Design Patterns


Design principles enhance design of a software system and address 3 main factors,
·        Rigidity – It is very hard to change
·        Fragility – break up of some parts as a side effect of modification
·        Immobility – hard to reuse either in same application or in some other
Design patterns suggests loose coupling between classes / modules. Making less dependent code minimizes the side effects of modifications.
Design Principles
  • Open Close Principle
  • Dependency Inversion Principle
  • Interface Segregation Principle
  • Single Responsibility Principle
  • Liskov's Substitution Principle
General Patterns
  • Lazy Load Pattern
  • Registry Pattern
Behavioral Patterns
  • Chain of Responsibility
  • Command
  • Interpreter
  • Iterator
  • Mediator
  • Mementr
  • Observer
  • Strategy
  • Template Method
  • Visitor
  • Null Object
Creational Patterns
  • Singleton
  • Factory
    • Factory Method
    • Abstract Factory
  • Builder
  • Prototype
  • Object Pool
Structural Patterns
  • Adapter
  • Bridge
  • Composite
  • Decorate
  • Flyweight
  • Proxy
Lazy load Pattern
Lazy loading the process of delaying the instantiation of an object until it is needed. Lazy programmers are the best programmers.

Registry Pattern
A registry is an object from which other objects can access data, settings and other details (even some objects) like a internal warehouse.

Open Close Principle
Open to extension and Close to modification. This pattern can be used when similar types of objects are kept adding.
E.g. Document /certificate are generated by a method / class. Whenever a certificate is added, a new class/method can be added instead of modifying existing class/method.

Dependency Inversion Principle
A high level class and low level class should be decoupled using abstraction, thereby reducing the dependency. Both the class should not depend on each other. They both should depend on the abstraction.
The term, inversion comes into play, abstraction should not be based on details. Details should be based on abstraction.
DIP pattern is applicable for places where frequent change is encountered.
E.g.




Interface Segregation Principle
Client should not be forced to use method(s) in an interface. Such interfaces with unwanted methods are called as polluted or fat interface. Instead of one such fat interface, many small interfaces can be created.
If a fat interface is designed already, they can be segregated using adapter pattern. Like other DP it requires time in analyzing the code and makes it complex but flexible.


Wrong Design
Interface reportProperties
{
        method setfilenam()
        method setfileProperties()
}
Class ExcelReport implements reportProperties
{
        method setfilename()
        method setfileProperties()
} // Excel can have both filename and file properties
Class HTMLReport implements reportProperties
{
        method setfilenam()
        method setfileProperties()
} // HTML can have only filename not file properties

Correct Design
Interface reportName
{
        method setfilename()
}
Interface reportProperties
{
        method setfileProperties()
}
Class ExcelReport implements reportName, reportProperties
{
        method setfilename ()
        method setfileProperties()
}
Class HTMLReport implements reportName
{
        method setfilenam()
}

Single Responsibility Principle
A class can have only one reason for modification in future. If there is more than a reason, then the class should be spitted to the number of reasons.

Liskov’s substitution Principle
The derived classes should not extend the super class behavior. This is just an extension of open-close principle.

Singleton
Singleton pattern is required when only one instance of a class should be allowed. This is required for critical operations which all users cannot perform. A centralized management is provided for internal and external resources with a global access point.
The class with singleton pattern instantiate itself not more than a time.
E.g. Backup, logging feature, factory implementation as singleton
Memento
A pattern for restoring internal state of an object, without violating encapsulation as a mean to restore the object to its initial / other state when required
This pattern when implemented has 3 components.
·        Memento – This component is usually a class stores the internal state of originator object. It implements two interfaces each for originator and caretaker.
The originator interface allows originator to store any number of state and access any state for restoration.
The Caretaker interface should not allow any operations or any access to the state stored by memento (encapsulation).
·        Originator – Creates a memento object and stores the originator (self) state into it. Fetch memento and restore the originator state.
·        Caretaker – stores a memento. Care taker cannot access memento i.e. communication is one way.
Example – database transactions and undo operations in common applications.

Observer
Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically
There are few events that trigger many actions. With respect to this pattern, the actions are observer of the trigger. Whenever an event happens it should communicate the changes or trigger the actions. This happens in one-to-many relation (can restrict to one to one also).
Consider an example, when an employee separate from an organization. This employee may have other responsibilities. He may be a supervisor for his sub-ordinates, member of a recruitment team. At all the places he should be replaced. Replace recommendation class for all additional works are observers of the basic separation class. The basic separation class is observable. Observer class and observable class stand at opposite ends.
A change in observable class should communicate that to all its observers. To make this happen both observer and observable class should follow an interface or an abstract class.
Observable
interface Observable
{
        function addObserver($observer); 
        // add observer classes which should trigger when a separation happens 
}
 
class separation implements Observable
{
        private $_observers = array();
 
        public function communicate( $name )
        {
               foreach( $this->_observers as $obs)
               {
                       $obs->separated($this, $name);
               }
        }
        public function addObserver($observer)
        {
               $this->_observers []= $observer;
        }
}
 
Observer
interface Observer
{
        function separated($sender, $args);
        // every observer should redefine this method with what to do in their   
           context
}

class recruiter implements Observer
{
        public function separated($objSeparator, $args)
        {
               echo "'$args' separated. Replace with a new recruiter to the    
                        panel" ;
        }
}
class supervisor implements Observer
{
        public function separated($objSeparator, $args)
        {
               echo "'$args' separated. Assign a new supervisor for his/her 
                       subordinates " ;
        }
}
 
Usage
$ul = new separation();
$ul->addObserver( new recruiter() );
$ul->addObserver( new supervisor() );
 
$ul->communicate( "Jack" );
 

 Strategy Pattern

Thursday, March 10, 2011

Spring Introduction

Inversion of Control - IoC:
IoC is a component of Spring framework, compose individual components into a fully equipped applications ready to use.
Spring framework have formalised design patterns as first-class objects which can be used readily in your applications.
Modules:
Core Container Core and Beans, Context and  Expression Language
Data Access / Integration JDBC, ORM, OXM, JMS and Transaction modules
Web Web, Web-Servlet, Web-Structs and Web-Portlet
AOP and Instrumentation
Test

Tuesday, February 1, 2011

Adobe Flash

          Adobe Flash Professional CS5 is used to create presentations, applications, and other content that responds to user interaction. Flash work includes simple animations, video content, user interfaces, applications .. etc.,. Simple applications contain basic animation. Rich applications can be made using pictures, sound, video, and special effects.
          There are 5 major parts when we work in flash environment:
  1. Stage
  2. Time line
  3. Tool Panel
  4. Property Inspector
  5. Library Panel

 

Tuesday, December 21, 2010

JSP- II

Expression Language:
          Expression Language is official from JSP 2.0. EL is used to do most of the thing what we did using Expression and declaration.
          Java in JSP impends, designers to know Java and Java in JSP is hard to maintain and change. For these reasons EL was required. EL isn't the replacement of java functionalities used in JSP pages. It is the convenient way to invoke java code. Plain old java methods are created somewhere else and calling using EL. EL always enclosed in curly braces, prefixed with $ like ${el}.
           With inclusion of EL, there is no need for scriplets in the pages. Even if there are some scriplets written, it can be easily ignored. Earlier this was done in the directive tags. Now it was done only at web.xml file.  
      <scripting-invalid>true</scripting-invalid> in jsp-config tag.
In the same way. EL can also be ignored in a page. But EL was enabled by default.
      <el-ignored>true</el-ignored> in jsp-config tag.



Monday, December 13, 2010

Java Servlet Pages - I

               JSP.. Java Server Pages is like other CGI scripting files which has HTML and scripting language specific code. Container transform JSP code into java source code and compiled into java servlet class. JSP is like that of other servlet class except that, it was written by the container.

JSP -> Servlet:
               JSP file was converted into a java servlet with name matching the jsp file. A service method was created with HTTP request and response as arguments. This service method will throw exceptions related to its operations. JSP file has as many as tags. Each tags are processed and corresponding servlet code was generated. Some of the processing are:
Directives are made as import
HTML tags are printed using out.write
Declarative tags are initialized
Expression tags are printed using print.
More information about these tags comes now....

Scriptlet:
               Scriptlet is the basic tag that takes any java code inside it.
Scriplet tag ~ <% ..... %>
A small variation in Open Scriptlet tag conveys different meaning to the container.

Directive
               Directive instructs container a special meaning other than poj. Directives are usually added at the beginning of the jsp file.
Directive tag ~ <%@ . 
Three ways Directive can be used:
  1. Page
  2. Include
  3. Taglib
               Each type is identified by the their name like <%@ page... %>, <%@ include... %> and <%@ taglib... %>.
These are like HTML tag attributes. Important thing is that there should not be any semi-colon in these tags.
    Page:
                   This directive specifies the package to be imported for this jsp file. Syntax will be of following patterns
    • <%@ page import="Lib.foo" %> ~ to import single class in a package.
    • <%@ page import="Lib.*" %> ~ to import all classes in a package.
    • <%@ page import="Lib.*, java.util.*" %> ~ to import classes from more than onepackage.
    Include:
    <releasing soon>
    Taglib:
    <releasing soon>

    Expression:
                   Expression is another tag type supported by JSP. Its like a printer, whatever you put inside gets printed. There is no need to put print statement to display it in pages.
    Expression tag ~ <%= ...... %>
    Statement inside the expression tag should not have a semi-colon. But why? Here it is, whatever inside the expression tag is treated as argument for print function. Putting semi-colon at the end means putting the semi-colon at the end of argument in the function call within "()".

    Declaration:
                   A variable can be declared in scriptlet and can be used in other tags. But each time when the service method 
    Declaration is a tag type inside which method and variable can be declared. These are static by nature i.e. whatever declared inside this declaration tag, gets printed outside the service class in the generated servlet.
    Declaration tag ~ <%! %>


    3 Methods:
                   The process and stages involved in converting a JSP file to servlet file need not to be known, except the interface that will be implemented by the servlet class and teh 3 methods.
    jspInit():
    This method is called from init() method. This can be overridden.
    jspDestroy():
    This method is called from destroy() method. This can be overridden.
    _jspService()
    This method is called from servlet's service method.  This makes a new thread for each  request and response. This methods cannot be overloaded or overridden


    Translation & Compilation:
                   This translation and compilation of JSP pages to servlet will take place only once for a page. It happens during the first client request. This process can even made before first client request. But it depends on the vendor who supports the feature. A query string "?jsp_precompile" when append on a jsp, the container translate and compile the file even without waiting for the first client request.

    Accessing Context parameters:
    Configuration in web.xml:
                   Initialising parameters for the page can be specified the same way as like that of a servlet. In addition to servlet mapping in web.xml, <jsp-file>xyz.jsp</jsp-file> tag should be added inside corresponding <servlet> tag.
    Overriding init method:
                   Method that initialises init parameters should be created in the name "jspInit". "jspInit" function should be created inside the declaration tag. This function will be called from init method of the translated servlet. Servlet context parameters are fetched and set to as attributes.
    Accessing Attributes:
                   In JSP, there is nothing called as context scoped. Even though attributes in application scope are bound to servlet context object. The attributes set in jspInit method can be accessed thur application.getAttribute("attribute name");

    Attribute Scope:
                   Servlets have only 3 attribute scope (context) .i.e Application. Request and Session.  JSP have one additional attribute scope i.e Page scope. With this page context reference, any other scoped attributes can be accessed. Access in the sense to get and set. 
                   The getAttribute and setAttribute methods of pageContext comes in two forms (overloaded). The overloaded methods takes one additional int argument. This int argument is to specify the context type.
    pageContext.getAttribute("foo", PageContext.SESSION_SCOPE)
    pageContext.getAttribute("foo", PageContext.APPLICATION_SCOPE)
    pageContext.setAttribute("foo", "asdf" ,PageContext.SESSION_SCOPE)
    pageContext.setAttribute("foo", "asdfsadfasfa",  PageContext.APPLICATION_SCOPE)

    Servlet

    Servlet:
    Servlets are protocols, platform independent server side component written in java language. Servlets can be used in any servlet enabled servers. It dynamically extend with java enabled servers.
    Primitive use of servlets is to serve HTTP request-response paradigm.

    As servlets run on server, they do not require GUI. Servlets are the server side counterparts of applets (Which runs on client).


    Sequence of Operation:

    • Container creates a request and response object.
    • Container creates a new thread and calls the service method of the servlet with the request and response objects.
    • The service method calls the method corresponds to the HTTP request type (POST. GET).
    • Servlet send the response to the client with the response object.
    • Request and Response object loses their scope. They are destroyed or ready for garbage collection.
    For each request container does not create new instance for a servlet. For each request, container assigns new thread to the same instance of the servlet.

    Life Cycle of Servlet:
    • Container loads the servlet class.
    • Container creates instance of the class. Servlets no-arg constructor is being called. So constructor cannot be re-written.
    • init() method is called. This can be overridden for various parameter initialisation and connectivity ..etc.,
    • Once initialized, servlet is ready to serve (service method doPost, doGet .., etc) client request.
    • Servlet gets destroyed.
    Container loads the servlet classes when the web-app is started or when the first client requests. Container gives choice to choose the mode. Even when it loads the servlet when the web-app loads, it will not service method will not run till it was initialised.