You are on page 1of 14

UML for Factory Method Pattern

o We are going to create a Plan abstract class and concrete classes that extends the Plan
abstract class. A factory class GetPlanFactory is defined as a next step.
o GenerateBill class will use GetPlanFactory to get a Plan object. It will pass information
(DOMESTICPLAN / COMMERCIALPLAN / INSTITUTIONALPLAN) to GetPalnFactory to get
the type of object it needs.

Calculate Electricity Bill : A Real World Example of Factory


Method
Step 1: Create a Plan abstract class.

1. import java.io.*;      
2. abstract class Plan{  
3.          protected double rate;  
4.          abstract void getRate();  
5.    
6.          public void calculateBill(int units){  
7.               System.out.println(units*rate);  
8.           }  
9. }//end of Plan class.  

Step 2: Create the concrete classes that extends Plan abstract class.

1. class  DomesticPlan extends Plan{  
2.         //@override  
3.          public void getRate(){  
4.              rate=3.50;              
5.         }  
6.    }//end of DomesticPlan class.  
1. class  CommercialPlan extends Plan{  
2.    //@override   
3.     public void getRate(){   
4.         rate=7.50;  
5.    }   
6. /end of CommercialPlan class.  
1. class  InstitutionalPlan extends Plan{  
2.    //@override  
3.     public void getRate(){   
4.         rate=5.50;  
5.    }   
6. /end of InstitutionalPlan class.  

Step 3: Create a GetPlanFactory to generate object of concrete classes based on given


information..

1. class GetPlanFactory{  
2.       
3.    //use getPlan method to get object of type Plan   
4.        public Plan getPlan(String planType){  
5.             if(planType == null){  
6.              return null;  
7.             }  
8.           if(planType.equalsIgnoreCase("DOMESTICPLAN")) {  
9.                  return new DomesticPlan();  
10.                }   
11.            else if(planType.equalsIgnoreCase("COMMERCIALPLAN")){  
12.                 return new CommercialPlan();  
13.             }   
14.           else if(planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {  
15.                 return new InstitutionalPlan();  
16.           }  
17.       return null;  
18.    }  
19. }//end of GetPlanFactory class.  

Step 4: Generate Bill by using the GetPlanFactory to get the object of concrete classes
by passing an information such as type of plan DOMESTICPLAN or COMMERCIALPLAN
or INSTITUTIONALPLAN.

1. import java.io.*;    
2. class GenerateBill{  
3.     public static void main(String args[])throws IOException{  
4.       GetPlanFactory planFactory = new GetPlanFactory();  
5.         
6.       System.out.print("Enter the name of plan for which the bill will be generated: ");  
7.       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
8.   
9.       String planName=br.readLine();  
10.       System.out.print("Enter the number of units for bill will be calculated: ");  
11.       int units=Integer.parseInt(br.readLine());  
12.   
13.       Plan p = planFactory.getPlan(planName);  
14.       //call getRate() method and calculateBill()method of DomesticPaln.  
15.   
16.        System.out.print("Bill amount for "+planName+" of  "+units+" units is: ");  
17.            p.getRate();  
18.            p.calculateBill(units);  
19.             }  
20.     }//end of GenerateBill class.  

A) UML diagram and the java implementation of Factory design pattern


The factory pattern is also called “Factory Method pattern” or “Virtual Constructor” in Java. In this
pattern, we create an interface or an abstract class with method declarations, and then the concrete
classes or subclasses implementing this interface or inheriting the class are responsible for creating
instances of the class.

Example let’s implement a generic shape interface. We can derive various concrete classes
from this interface like the circle, rectangle, etc. Then we will have a shape Factory class that
will access the concrete class objects.

The UML for factory pattern is shown below.


As already explained this is the UML diagram for factory pattern. Now we will implement a Java
program demonstrating the factory pattern.

package factory_pattern;

/**
*
* @author Urgesa
*/
interface Geometric_shape {
void draw_shape();
}

//Geometric shape classes implementing Geometric_shape interface


class Rectangle implements Geometric_shape {
@Override
public void draw_shape() {
System.out.println("Rectangle class::draw_shape() method.");
}
}
class Square implements Geometric_shape {
@Override
public void draw_shape() {
System.out.println("Square class::draw_shape() method.");
}
}

class Circle implements Geometric_shape {


@Override
public void draw_shape() {
System.out.println("Circle class::draw_shape() method.");
}
}
//Factory class for Geometric_shape
class ShapeFactory {
//shapeObject method gets particular shapeType (circle, Square or Rectangle)
public Geometric_shape shapeObject(String shapeType){
if(shapeType == null){
return null;
}
//retrieve Circle object
if(shapeType.equalsIgnoreCase("Circle")){
return new Circle();

//retrieve Rectangle object


} else if(shapeType.equalsIgnoreCase("Rectangle")){
return new Rectangle();

////retrieve Square object


} else if(shapeType.equalsIgnoreCase("Square")){
return new Square();
}
return null;
}
}
public class Factory_Pattern {

public static void main(String[] args) {


//Create a ShapeFactory object to get different geometric shapes
ShapeFactory shapeFactory = new ShapeFactory();

//circle
Geometric_shape shape_Circle = shapeFactory.shapeObject("CIRCLE");

//draw method of Circle


shape_Circle.draw_shape();

//Rectangle
Geometric_shape shape_Rectangle = shapeFactory.shapeObject("RECTANGLE");

//draw method of Rectangle


shape_Rectangle.draw_shape();

//Square
Geometric_shape shape_Square = shapeFactory.shapeObject("SQUARE");

//draw method of square


shape_Square.draw_shape();
}
}//end of factory pattern

Output Factory Pattern

 
B)UML diagram and the java implementation for Singleton design
pattern
Implementation of the Singleton Pattern

As already mentioned, a singleton design pattern restricts the class with only one instance and this
instance is given a global point of access. This was all classes that refer to the same object again and
again.

The following UML diagram explains the Singleton pattern.

This implementation of this singleton class as explained above is shown in the Java
program below.
package singleobject;

class SingletonObject {

//create an object of SingletonObject

private static SingletonObject instance = new SingletonObject();

//private constructor so that we cannot instantiate the class

private SingletonObject(){}
//returns the only available object

public static SingletonObject getInstance(){

return instance;

public void printMessage(){

System.out.println("Hello from Singleton object!!!");

public class Main {

public static void main(String[] args) {

//illegal statement because constructor is private

//Compile Time Error: The constructor SingletonObject() is not visible

//SingletonObject object = new SingletonObject();

//call getInstance to retrieve the object available from the class

SingletonObject object = SingletonObject.getInstance();

//show the message

object.printMessage();

Output for singleton object


c) UML diagram and the java implementation for Adapter design
pattern

Uml design for adapter design pattern


This adapter pattern uses multiple polymorphic interfaces implementing or inheriting both the
interface that is expected and the interface that is pre-existing. It is typical for the expected
interface to be created as a pure interface class, especially in languages such as Java (before JDK
1.8) that do not support multiple inheritance of classes.

The class adapter pattern expressed in UML

The class adapter pattern expressed in LePUS3


Implementation of the adapter pattern by java
When implementing the adapter pattern, for clarity, one can apply the class name  [ClassName]
to [Interface]Adapter  to the provider implementation; for example,  DAOToProviderAdapter . It
should have a constructor method with an adaptee class variable as a parameter. This parameter
will be passed to an instance member of  [ClassName] to [Interface] Adapter . When the
clientMethod is called, it will have access to the adaptee instance that allows for accessing the
required data of the adaptee and performing operations on that data that generates the desired
output.

Implementation as follow

package adapterdemo;

interface LightningPhone {

void recharge();

void useLightning();

interface MicroUsbPhone {

void recharge();

void useMicroUsb();

class Iphone implements LightningPhone {

private boolean connector;

@Override

public void useLightning() {

connector = true;

System.out.println("Lightning connected");

}
@Override

public void recharge() {

if (connector) {

System.out.println("Recharge started");

System.out.println("Recharge finished");

} else {

System.out.println("Connect Lightning first");

class Android implements MicroUsbPhone {

private boolean connector;

@Override

public void useMicroUsb() {

connector = true;

System.out.println("MicroUsb connected");

@Override

public void recharge() {

if (connector) {

System.out.println("Recharge started");

System.out.println("Recharge finished");

} else {

System.out.println("Connect MicroUsb first");

}
}

/* exposing the target interface while wrapping source object */

class LightningToMicroUsbAdapter implements MicroUsbPhone {

private final LightningPhone lightningPhone;

public LightningToMicroUsbAdapter(LightningPhone lightningPhone) {

this.lightningPhone = lightningPhone;

@Override

public void useMicroUsb() {

System.out.println("MicroUsb connected");

lightningPhone.useLightning();

@Override

public void recharge() {

lightningPhone.recharge();

public class AdapterDemo {

static void rechargeMicroUsbPhone(MicroUsbPhone phone) {

phone.useMicroUsb();

phone.recharge();

static void rechargeLightningPhone(LightningPhone phone) {


phone.useLightning();

phone.recharge();

public static void main(String[] args) {

Android android = new Android();

Iphone iPhone = new Iphone();

System.out.println("Recharging android with MicroUsb");

rechargeMicroUsbPhone(android);

System.out.println("Recharging iPhone with Lightning");

rechargeLightningPhone(iPhone);

System.out.println("Recharging iPhone with MicroUsb");

rechargeMicroUsbPhone(new LightningToMicroUsbAdapter (iPhone));

0utput for adapter pattern

You might also like