Friday, 29 April 2016

Waterfall Model

The Waterfall Model was first Process Model to be introduced. It is also referred to as a linear-sequential life cycle model. It is very simple to understand and use. In a waterfall model, each phase must be completed before the next phase can begin and there is no overlapping in the phases.
Waterfall model is the earliest SDLC approach that was used for software development .
The waterfall Model illustrates the software development process in a linear sequential flow; hence it is also referred to as a linear-sequential life cycle model. This means that any phase in the development process begins only if the previous phase is complete. In waterfall model phases do not overlap.

Waterfall Model design

Waterfall approach was first SDLC Model to be used widely in Software Engineering to ensure success of the project. In "The Waterfall" approach, the whole process of software development is divided into separate phases. In Waterfall model, typically, the outcome of one phase acts as the input for the next phase sequentially.
Following is a diagrammatic representation of different phases of waterfall model.
SDLC Waterfall Model
The sequential phases in Waterfall model are:
  • Requirement Gathering and analysis: All possible requirements of the system to be developed are captured in this phase and documented in a requirement specification doc.
  • System Design: The requirement specifications from first phase are studied in this phase and system design is prepared. System Design helps in specifying hardware and system requirements and also helps in defining overall system architecture.
  • Implementation: With inputs from system design, the system is first developed in small programs called units, which are integrated in the next phase. Each unit is developed and tested for its functionality which is referred to as Unit Testing.
  • Integration and Testing: All the units developed in the implementation phase are integrated into a system after testing of each unit. Post integration the entire system is tested for any faults and failures.
  • Deployment of system: Once the functional and non functional testing is done, the product is deployed in the customer environment or released into the market.
  • Maintenance: There are some issues which come up in the client environment. To fix those issues patches are released. Also to enhance the product some better versions are released. Maintenance is done to deliver these changes in the customer environment.
All these phases are cascaded to each other in which progress is seen as flowing steadily downwards (like a waterfall) through the phases. The next phase is started only after the defined set of goals are achieved for previous phase and it is signed off, so the name "Waterfall Model". In this model phases do not overlap.

Waterfall Model Application

Every software developed is different and requires a suitable SDLC approach to be followed based on the internal and external factors. Some situations where the use of Waterfall model is most appropriate are:
  • Requirements are very well documented, clear and fixed.
  • Product definition is stable.
  • Technology is understood and is not dynamic.
  • There are no ambiguous requirements.
  • Ample resources with required expertise are available to support the product.
  • The project is short.

Waterfall Model Pros & Cons

Advantage

The advantage of waterfall development is that it allows for departmentalization and control. A schedule can be set with deadlines for each stage of development and a product can proceed through the development process model phases one by one.
Development moves from concept, through design, implementation, testing, installation, troubleshooting, and ends up at operation and maintenance. Each phase of development proceeds in strict order.

Disadvantage

The disadvantage of waterfall development is that it does not allow for much reflection or revision. Once an application is in the testing stage, it is very difficult to go back and change something that was not well-documented or thought upon in the concept stage.
The following table lists out the pros and cons of Waterfall model:
ProsCons
  • Simple and easy to understand and use
  • Easy to manage due to the rigidity of the model . each phase has specific deliverables and a review process.
  • Phases are processed and completed one at a time.
  • Works well for smaller projects where requirements are very well understood.
  • Clearly defined stages.
  • Well understood milestones.
  • Easy to arrange tasks.
  • Process and results are well documented.
  • No working software is produced until late during the life cycle.
  • High amounts of risk and uncertainty.
  • Not a good model for complex and object-oriented projects.
  • Poor model for long and ongoing projects.
  • Not suitable for the projects where requirements are at a moderate to high risk of changing. So risk and uncertainty is high with this process model.
  • It is difficult to measure progress within stages.
  • Cannot accommodate changing requirements.
  • Adjusting scope during the life cycle can end a project.
  • Integration is done as a "big-bang. at the very end, which doesn't allow identifying any technological or business bottleneck or challenges early.

Agile SDLC

Agile SDLC model is a combination of iterative and incremental process models with focus on process adaptability and customer satisfaction by rapid delivery of working software product.
Agile Methods break the product into small incremental builds. These builds are provided in iterations. Each iteration typically lasts from about one to three weeks. Every iteration involves cross functional teams working simultaneously on various areas like planning, requirements analysis, design, coding, unit testing, and acceptance testing.
At the end of the iteration a working product is displayed to the customer and important stakeholders.

What is Agile?

Agile model believes that every project needs to be handled differently and the existing methods need to be tailored to best suit the project requirements. In agile the tasks are divided to time boxes (small time frames) to deliver specific features for a release.
Iterative approach is taken and working software build is delivered after each iteration. Each build is incremental in terms of features; the final build holds all the features required by the customer.
Here is a graphical illustration of the Agile Model:
SDLC Agile Model
Agile thought process had started early in the software development and started becoming popular with time due to its flexibility and adaptability.
The most popular agile methods include Rational Unified Process (1994), Scrum (1995), Crystal Clear, Extreme Programming (1996), Adaptive Software Development, Feature Driven Development, and Dynamic Systems Development Method (DSDM) (1995). These are now collectively referred to as agile methodologies, after the Agile Manifesto was published in 2001.
Following are the Agile Manifesto principles
  • Individuals and interactions - in agile development, self-organization and motivation are important, as are interactions like co-location and pair programming.
  • Working software - Demo working software is considered the best means of communication with the customer to understand their requirement, instead of just depending on documentation.
  • Customer collaboration - As the requirements cannot be gathered completely in the beginning of the project due to various factors, continuous customer interaction is very important to get proper product requirements.
  • Responding to change - agile development is focused on quick responses to change and continuous development.

Agile Vs Traditional SDLC Models

Agile is based on the adaptive software development methods where as the traditional SDLC models like waterfall model is based on predictive approach.
Predictive teams in the traditional SDLC models usually work with detailed planning and have a complete forecast of the exact tasks and features to be delivered in the next few months or during the product life cycle. Predictive methods entirely depend on the requirement analysis and planning done in the beginning of cycle. Any changes to be incorporated go through a strict change control management and prioritization.
Agile uses adaptive approach where there is no detailed planning and there is clarity on future tasks only in respect of what features need to be developed. There is feature driven development and the team adapts to the changing product requirements dynamically. The product is tested very frequently, through the release iterations, minimizing the risk of any major failures in future.
Customer interaction is the backbone of Agile methodology, and open communication with minimum documentation are the typical features of Agile development environment. The agile teams work in close collaboration with each other and are most often located in the same geographical location.


Why Agile?


Agile development methodology provides opportunities to assess the direction of a project throughout the development lifecycle. This is achieved through regular cadences of work, known as sprints or iterations, at the end of which teams must present a potentially shippable product increment. By focusing on the repetition of abbreviated work cycles as well as the functional product they yield, agile methodology is described as “iterative” and “incremental.” In waterfall, development teams only have one chance to get each aspect of a project right. In an agile paradigm, every aspect of development — requirements, design, etc. — is continually revisited throughout the lifecycle. When a team stops and re-evaluates the direction of a project every two weeks, there’s always time to steer it in another direction.
The results of this “inspect-and-adapt” approach to development greatly reduce both development costs and time to market. Because teams can develop software at the same time they’re gathering requirements, the phenomenon known as “analysis paralysis” is less likely to impede a team from making progress. And because a team’s work cycle is limited to two weeks, it gives stakeholders recurring opportunities to calibrate releases for success in the real world. Agile development methodology helps companies build the right product. Instead of committing to market a piece of software that hasn’t even been written yet, agile empowers teams to continuously replan their release to optimize its value throughout development, allowing them to be as competitive as possible in the marketplace. Development using an agile methodology preserves a product’s critical market relevance and ensures a team’s work doesn’t wind up on a shelf, never released.

  • The agile software development emphasizes on four core values.

  1. Individual and team interactions over processes and tools
  2. Working software over comprehensive documentation
  3. Customer collaboration over contract negotiation
  4. Responding to change over following a plan

Agile versus Waterfall Method

Agile and Waterfall model are two different methods for software development process. Though they are different in their approach, both methods are useful at times, depending on the requirement and the type of the project.
Agile Model
Waterfall Model
  • Agile method proposes incremental and iterative approach to software design
  • Development of the software flows sequentially from start point to end point.
  • The agile process is broken into individual models that designers work on
  • The design process is not broken into an individual models
  • The customer has early and frequent opportunities to look at the product and make decision and changes to the project
  • The customer can only see the product at the end of the project
  • Agile model is considered unstructured compared to the waterfall model
  • Waterfall model are more secure because they are so plan oriented
  • Small projects can be implemented very quickly. For large projects, it is difficult to estimate the development time.
  • All sorts of project can be estimated and completed.
  • Error can be fixed in the middle of the project.
  • Only at the end, the whole product is tested. If the requirement error is found or any changes have to be made, the project has to start from the beginning
  • Development process is iterative, and the project is executed in short (2-4) weeks iterations. Planning is very less.
  • The development process is phased, and the phase is much bigger than iteration. Every phase ends with the detailed description of the next phase.
  • Documentation attends less priority than software development
  • Documentation is a top priority and can even use for training staff and upgrade the software with another team
  • Every iteration has its own testing phase. It allows implementing regression testing every time new functions or logic are released.
  • Only after the development phase, the testing phase is executed because separate parts are not fully functional.
  • In agile testing when an iteration end, shippable features of the product is delivered to the customer. New features are usable right after shipment. It is useful when you have good contact with customers.
  • All features developed are delivered at once after the long implementation phase.
  • Testers and developers work together
  • Testers work separately from developers
  • At the end of every sprint, user acceptance is performed
  • User acceptance is performed at the end of the project.
  • It requires close communication with developers and together analyse requirements and planning
  • Developer does not involve in requirement and planning process. Usually, time delays between tests and coding

Methodologies of Agile Testing

There are various methods present in agile testing, and those are listed below:

Scrum

SCRUM is an agile development method which concentrates specifically on how to manage tasks within a team based development environment. Basically, Scrum is derived from activity that occurs during a rugby match. Scrum believes in empowering the development team and advocates working in small teams (say- 7 to 9 members). It consists of three roles, and their responsibilities are explained as follows:
  • Scrum Master
    • Master is responsible for setting up the team, sprint meeting and removes obstacles to progress
  • Product owner
    • The Product Owner creates product backlog, prioritizes the backlog and is responsible for the delivery of the functionality at each iteration
  • Scrum Team
    • Team manages its own work and organizes the work to complete the sprint or cycle

Product Backlog

This is a repository where requirements are tracked with details on the no of requirements to be completed for each release. It should be maintained and prioritized by product owner, and it should be distributed to the scrum team. Team can also request for a new requirement addition or modification or deletion

Scrum Practices

Practices are described in detailed:

Process flow of Scrum:

Process flow of scrum testing is as follows:
  • Each iteration of a scrum is known as Sprint
  • Product backlog is a list where all details are entered to get end product
  • During each Sprint, top items of Product backlog are selected and turned into Sprint backlog
  • Team works on the defined sprint backlog
  • Team checks for the daily work
  • At the end of the sprint, team delivers product functionality

eXtreme Programming (XP)

Extreme Programming technique is very helpful when there is constantly changing demands or requirements from the customers or when they are not sure about the functionality of the system. It advocates frequent "releases" of the product in short development cycles, which inherently improves the productivity of the system and also introduces a checkpoint where any customer requirements can be easily implemented. The XP develops software keeping customer in the target.
Business requirements are gathered in terms of stories. All those stories are stored in a place called the parking lot.
In this type of methodology, releases are based on the shorter cycles called Iterations with span of 14 days time period. Each iteration includes phases like coding, unit testing and system testing where at each phase some minor or major functionality will be built in the application.

Phases of eXtreme programming:

There are 6 phases available in Agile XP method, and those are explained as follows:

Planning

  • Identification of stakeholders and sponsors
  • Infrastructure Requirements
  • Security related information and gathering
  • Service Level Agreements and its conditions

Analysis

  • Capturing of Stories in Parking lot
  • Prioritize stories in Parking lot
  • Scrubbing of stories for estimation
  • Define Iteration SPAN(Time)
  • Resource planning for both Development and QA teams

Design

  • Break down of tasks
  • Test Scenario preparation for each task
  • Regression Automation Framework

Execution

  • Coding
  • Unit Testing
  • Execution of Manual test scenarios
  • Defect Report generation
  • Conversion of Manual to Automation regression test cases
  • Mid Iteration review
  • End of Iteration review

Wrapping

  • Small Releases
  • Regression Testing
  • Demos and reviews
  • Develop new stories based on the need
  • Process Improvements based on end of iteration review comments

Closure

  • Pilot Launch
  • Training
  • Production Launch
  • SLA Guarantee assurance
  • Review SOA strategy
  • Production Support
There are two storyboards available to track the work on a daily basis, and those are listed below for reference.
  • Story Cardboard
    • This is a traditional way of collecting all the stories in a board in the form of stick notes to track daily XP activities. As this manual activity involves more effort and time, it is better to switch to an online form.

  • Online Storyboard
    • Online tool Storyboard can be used to store the stories. Several teams can use it for different purposes.

Crystal Methodologies

Crystal Methodology is based on three concepts
  1. Chartering: Various activities involved in this phase are creating a development team, performing a preliminary feasibility analysis, developing an initial plan and fine-tuning the development methodology
  2. Cyclic delivery: The main development phase consists of two or more delivery cycles, during which the
    1. Team updates and refines the release plan
    2. Implements a subset of the requirements through one or more program test integrate iterations
    3. Integrated product is delivered to real users
    4. Review of the project plan and adopted development methodology
  3. Wrap Up: The activities performed in this phase are deployment into the user environment, post- deployment reviews and reflections are performed.

Dynamic Software Development Method (DSDM)

DSDM is a Rapid Application Development (RAD) approach to software development and provides an agile project delivery framework. The important aspect of DSDM is that the users are required to be involved actively, and the teams are given the power to make decisions. Frequent delivery of product becomes the active focus with DSDM. The techniques used in DSDM are
  1. Time Boxing
  2. MoSCoW Rules
  3. Prototyping
The DSDM project consists of 7 phases
  1. Pre-project
  2. Feasibility Study
  3. Business Study
  4. Functional Model Iteration
  5. Design and build Iteration
  6. Implementation
  7. Post-project

Feature Driven Development (FDD)

This method is focused around "designing & building" features. Unlike other agile methods, FDD describes very specific and short phases of work that has to be accomplished separately per feature. It includes domain walkthrough, design inspection, promote to build, code inspection and design. FDD develops product keeping following things in the target
  1. Domain object Modeling
  2. Development by feature
  3. Component/ Class Ownership
  4. Feature Teams
  5. Inspections
  6. Configuration Management
  7. Regular Builds
  8. Visibility of progress and results

Lean Software Development

Lean software development method is based on the principle "Just in time production". It aims at increasing speed of software development and decreasing cost. Lean development can be summarized in seven steps.
  1. Eliminating Waste
  2. Amplifying learning
  3. Defer commitment (deciding as late as possible)
  4. Early delivery
  5. Empowering the team
  6. Building Integrity
  7. Optimize the whole

Kanban

Kanban originally emerged from Japanese word that means, a card containing all the information needed> to be done on the product at each stage along its path to completion. This framework or method is quite adopted in software testing method especially in agile testing.

Difference between Scrum and Kanban

Scrum
Kanban
  • In scrum technique, test must be broken down so that they can be completed within one sprint
  • No particular item size is prescribed
  • Prescribes a prioritized product backlog
  • Prioritization is optional
  • Scrum team commits to a particular amount of work for the iteration
  • Commitment is optional
  • Burndown chart is prescribed
  • No particular item size is prescribed
  • Between each sprint, a scrum board is reset
  • A Kanban board is persistent. It limits the number of items in workflow state
  • It cannot add items to ongoing iteration
  • It can add items whenever capacity is available
  • WIP limited indirectly
  • WIP limited directly
  • Timeboxed iterations prescribed
  • Timeboxed iterations optional

Agile metrics:

Metrics that can be collected for effective usage of Agile is:
  • Drag Factor
    • Effort in hours which do not contribute to sprint goal
    • Drag factor can be improved by reducing number of shared resources, reducing the amount of non-contributing work
    • New estimates can be increased by percentage of drag factor -New estimate = (Old estimate+drag factor)
  • Velocity
    • Amount of backlog converted to shippable functionality of sprint
  • No of Unit Tests added
  • Time taken to complete daily build
  • Bugs detected in an iteration or in previous iterations
  • Production defect leakage

Design Patterns




Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time.
In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book titled Design Patterns - Elements of Reusable Object-Oriented Software which initiated the concept of Design Pattern in Software development. These authors are collectively known as Gang of Four (GOF).
Design patterns can be classified in three categories: Creational, Structural and Behavioral patterns.
  • Creational Patterns - These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new opreator. This gives program more flexibility in deciding which objects need to be created for a given use case.
  • Structural Patterns - These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities.
  • Behavioral Patterns - These design patterns are specifically concerned with communication between objects.
These design patterns are specifically concerned with the presentation tier. These patterns are identified by Sun Java Center.
Factory pattern is one of most used design pattern in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

Step 1

Create an interface.
Shape.java
public interface Shape {
   void draw();
}

Step 2

Create concrete classes implementing the same interface.
Rectangle.java
public class Rectangle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}
Square.java
public class Square implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}
Circle.java
public class Circle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

Step 3

Create a Factory to generate object of concrete class based on given information.
ShapeFactory.java
public class ShapeFactory {
 
   //use getShape method to get object of type shape 
   public Shape getShape(String shapeType){
      if(shapeType == null){
         return null;
      }  
      if(shapeType.equalsIgnoreCase("CIRCLE")){
         return new Circle();
         
      } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();
         
      } else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      }
      
      return null;
   }
}

Step 4

Use the Factory to get object of concrete class by passing an information such as type.
FactoryPatternDemo.java
public class FactoryPatternDemo {

   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();

      //get an object of Circle and call its draw method.
      Shape shape1 = shapeFactory.getShape("CIRCLE");

      //call draw method of Circle
      shape1.draw();

      //get an object of Rectangle and call its draw method.
      Shape shape2 = shapeFactory.getShape("RECTANGLE");

      //call draw method of Rectangle
      shape2.draw();

      //get an object of Square and call its draw method.
      Shape shape3 = shapeFactory.getShape("SQUARE");

      //call draw method of circle
      shape3.draw();
   }
}

Step 5

Verify the output.
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.
Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern.

Step 1

Create an interface for Shapes.
Shape.java
public interface Shape {
   void draw();
}

Step 2

Create concrete classes implementing the same interface.
Rectangle.java
public class Rectangle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}
Square.java
public class Square implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}
Circle.java
public class Circle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

Step 3

Create an interface for Colors.
Color.java
public interface Color {
   void fill();
}

Step4

Create concrete classes implementing the same interface.
Red.java
public class Red implements Color {

   @Override
   public void fill() {
      System.out.println("Inside Red::fill() method.");
   }
}
Green.java
public class Green implements Color {

   @Override
   public void fill() {
      System.out.println("Inside Green::fill() method.");
   }
}
Blue.java
public class Blue implements Color {

   @Override
   public void fill() {
      System.out.println("Inside Blue::fill() method.");
   }
}

Step 5

Create an Abstract class to get factories for Color and Shape Objects.
AbstractFactory.java
public abstract class AbstractFactory {
   abstract Color getColor(String color);
   abstract Shape getShape(String shape) ;
}

Step 6

Create Factory classes extending AbstractFactory to generate object of concrete class based on given information.
ShapeFactory.java
public class ShapeFactory extends AbstractFactory {
 
   @Override
   public Shape getShape(String shapeType){
   
      if(shapeType == null){
         return null;
      }  
      
      if(shapeType.equalsIgnoreCase("CIRCLE")){
         return new Circle();
         
      }else if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();
         
      }else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      }
      
      return null;
   }
   
   @Override
   Color getColor(String color) {
      return null;
   }
}
ColorFactory.java
public class ColorFactory extends AbstractFactory {
 
   @Override
   public Shape getShape(String shapeType){
      return null;
   }
   
   @Override
   Color getColor(String color) {
   
      if(color == null){
         return null;
      }  
      
      if(color.equalsIgnoreCase("RED")){
         return new Red();
         
      }else if(color.equalsIgnoreCase("GREEN")){
         return new Green();
         
      }else if(color.equalsIgnoreCase("BLUE")){
         return new Blue();
      }
      
      return null;
   }
}

Step 7

Create a Factory generator/producer class to get factories by passing an information such as Shape or Color
FactoryProducer.java
public class FactoryProducer {
   public static AbstractFactory getFactory(String choice){
   
      if(choice.equalsIgnoreCase("SHAPE")){
         return new ShapeFactory();
         
      }else if(choice.equalsIgnoreCase("COLOR")){
         return new ColorFactory();
      }
      
      return null;
   }
}

Step 8

Use the FactoryProducer to get AbstractFactory in order to get factories of concrete classes by passing an information such as type.
AbstractFactoryPatternDemo.java
public class AbstractFactoryPatternDemo {
   public static void main(String[] args) {

      //get shape factory
      AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");

      //get an object of Shape Circle
      Shape shape1 = shapeFactory.getShape("CIRCLE");

      //call draw method of Shape Circle
      shape1.draw();

      //get an object of Shape Rectangle
      Shape shape2 = shapeFactory.getShape("RECTANGLE");

      //call draw method of Shape Rectangle
      shape2.draw();
      
      //get an object of Shape Square 
      Shape shape3 = shapeFactory.getShape("SQUARE");

      //call draw method of Shape Square
      shape3.draw();

      //get color factory
      AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR");

      //get an object of Color Red
      Color color1 = colorFactory.getColor("RED");

      //call fill method of Red
      color1.fill();

      //get an object of Color Green
      Color color2 = colorFactory.getColor("Green");

      //call fill method of Green
      color2.fill();

      //get an object of Color Blue
      Color color3 = colorFactory.getColor("BLUE");

      //call fill method of Color Blue
      color3.fill();
   }
}

Step 9

Verify the output.
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.
Inside Red::fill() method.
Inside Green::fill() method.
Inside Blue::fill() method.
Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

Step 1

Create a Singleton Class.
SingleObject.java
public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }

   public void showMessage(){
      System.out.println("Hello World!");
   }
}

Step 2

Get the only object from the singleton class.
SingletonPatternDemo.java
public class SingletonPatternDemo {
   public static void main(String[] args) {

      //illegal construct
      //Compile Time Error: The constructor SingleObject() is not visible
      //SingleObject object = new SingleObject();

      //Get the only object available
      SingleObject object = SingleObject.getInstance();

      //show the message
      object.showMessage();
   }
}

Step 3

Verify the output.
Hello World!

Another Example:
public sealed class Singleton
{
     private Singleton()
     {
     }
      private static Singleton obj;
      public static Singleton Instance()
      {
         if obj== null)
         {
            obj= new Singleton();
          }
             return obj;
      }

     // supporting objects
     public Currency objCurrency = new Currency();
     public Country objCountry = new Country();

}

// supporting classes
public class Currency
{
      public int CurrencyId { get; set; }
      public string CurrencyName { get; set; }
      public List <Currency> getCurrency(int x=0)
      {
          List<Currency> lst = new List<Currency>();
          lst.Add(new Currency { CurrencyId = 1, CurrencyName = "INR" });
          lst.Add(new Currency { CurrencyId = 2, CurrencyName = "USD" });
          lst.Add(new Currency { CurrencyId = 3, CurrencyName = "EURO" });
          lst.Add(new Currency { CurrencyId = 4, CurrencyName = "YEN" });

           if (x > 0)
           {
             lst.Add(new Currency { CurrencyId = 5, CurrencyName = "NEW ***" });
           }
             return lst;
    }

}

public class Country       
{
    public int CountryId { get; set; }
    public string CountryName { get; set; }
    public List<Country> getCountry(int x=0)
    {
        List<Country> lst = new List<Country>();
        lst.Add(new Country { CountryId = 1, CountryName = "INDIA" });
        lst.Add(new Country { CountryId = 2, CountryName = "USA" });
        lst.Add(new Country { CountryId = 3, CountryName = "UK" });
        lst.Add(new Country { CountryId = 4, CountryName = "JAPAN" });
         if (x > 0)
         {
             lst.Add(new Country { CountryId = 5, CountryName = "SAMPLE ***" });
         }
            return lst;
    }
}

}

// use

Singleton obj = Singleton.Instance();
var a = obj.objCountry.getCountry();
var b = obj.objCurrency.getCurrency();

Singleton obj1 = Singleton.Instance();
var c = obj1.objCountry.getCountry(1);
var d = obj1.objCurrency.getCurrency(1);

Singleton obj2 = Singleton.Instance();
var e = obj2.objCountry.getCountry();

var f = obj2.objCurrency.getCurrency();

It is two step process. First, make the constructor private so that new operator cannot be used to instantiate the class. Return an object of the object if not null otherwise create the object and return the same via a method.

Step 1

Create an interface Item representing food item and packing.
Item.java
public interface Item {
   public String name();
   public Packing packing();
   public float price(); 
}
Packing.java
public interface Packing {
   public String pack();
}

Step 2

Create concrete classes implementing the Packing interface.
Wrapper.java
public class Wrapper implements Packing {

   @Override
   public String pack() {
      return "Wrapper";
   }
}
Bottle.java
public class Bottle implements Packing {

   @Override
   public String pack() {
      return "Bottle";
   }
}

Step 3

Create abstract classes implementing the item interface providing default functionalities.
Burger.java
public abstract class Burger implements Item {

   @Override
   public Packing packing() {
      return new Wrapper();
   }

   @Override
   public abstract float price();
}
ColdDrink.java
public abstract class ColdDrink implements Item {

 @Override
 public Packing packing() {
       return new Bottle();
 }

 @Override
 public abstract float price();
}

Step 4

Create concrete classes extending Burger and ColdDrink classes
VegBurger.java
public class VegBurger extends Burger {

   @Override
   public float price() {
      return 25.0f;
   }

   @Override
   public String name() {
      return "Veg Burger";
   }
}
ChickenBurger.java
public class ChickenBurger extends Burger {

   @Override
   public float price() {
      return 50.5f;
   }

   @Override
   public String name() {
      return "Chicken Burger";
   }
}
Coke.java
public class Coke extends ColdDrink {

   @Override
   public float price() {
      return 30.0f;
   }

   @Override
   public String name() {
      return "Coke";
   }
}
Pepsi.java
public class Pepsi extends ColdDrink {

   @Override
   public float price() {
      return 35.0f;
   }

   @Override
   public String name() {
      return "Pepsi";
   }
}

Step 5

Create a Meal class having Item objects defined above.
Meal.java
import java.util.ArrayList;
import java.util.List;

public class Meal {
   private List<Item> items = new ArrayList<Item>(); 

   public void addItem(Item item){
      items.add(item);
   }

   public float getCost(){
      float cost = 0.0f;
      
      for (Item item : items) {
         cost += item.price();
      }  
      return cost;
   }

   public void showItems(){
   
      for (Item item : items) {
         System.out.print("Item : " + item.name());
         System.out.print(", Packing : " + item.packing().pack());
         System.out.println(", Price : " + item.price());
      }  
   } 
}

Step 6

Create a MealBuilder class, the actual builder class responsible to create Meal objects.
MealBuilder.java
public class MealBuilder {

   public Meal prepareVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new VegBurger());
      meal.addItem(new Coke());
      return meal;
   }   

   public Meal prepareNonVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new ChickenBurger());
      meal.addItem(new Pepsi());
      return meal;
   }
}

Step 7

BuiderPatternDemo uses MealBuider to demonstrate builder pattern.
BuilderPatternDemo.java
public class BuilderPatternDemo {
   public static void main(String[] args) {
   
      MealBuilder mealBuilder = new MealBuilder();

      Meal vegMeal = mealBuilder.prepareVegMeal();
      System.out.println("Veg Meal");
      vegMeal.showItems();
      System.out.println("Total Cost: " + vegMeal.getCost());

      Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
      System.out.println("\n\nNon-Veg Meal");
      nonVegMeal.showItems();
      System.out.println("Total Cost: " + nonVegMeal.getCost());
   }
}

Step 8

Verify the output.
Veg Meal
Item : Veg Burger, Packing : Wrapper, Price : 25.0
Item : Coke, Packing : Bottle, Price : 30.0
Total Cost: 55.0


Non-Veg Meal
Item : Chicken Burger, Packing : Wrapper, Price : 50.5
Item : Pepsi, Packing : Bottle, Price : 35.0
Total Cost: 85.5
Following are the differences between a static class and a singleton class.
  • A static class can not be a top level class and can not implement interfaces where a singleton class can.
  • All members of a static class are static but for a Singleton class it is not a requirement.
  • A static class get initialized when it is loaded so it can not be lazily loaded where a singleton class can be lazily loaded.
  • A static class object is stored in stack whereas singlton class object is stored in heap memory space.
Yes.
Throw exception within the body of clone() method.
Following are some of the design patterns which are used in JDK library.
  • Decorator patttern is used by Wrapper classes.
  • Singleton pattern is used by Runtime, Calendar classes.
  • Factory pattern is used by Wrapper class like Integer.valueOf.
  • Observer pattern is used by event handling frameworks like swing, awt.
Factory pattern encapsulates the implementation details and underlying implementation can be changed without any impact on caller api.
Builder pattern builds a complex object using simple objects and using a step by step approach. This builder is independent of other objects.
Prototype pattern refers to creating duplicate object while keeping performance in mind. This pattern involves implementing a prototype interface which tells to create a clone of the current object.
This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.