SlideShare a Scribd company logo
Creational Pattern - 2
By,
D. B. Naga Muruga,
Dept of Mechanical Engineering,
Sriram Engineering College
Abstract factory Pattern
 Define abstract factory pattern
Definition
Provides one level of interface higher than the factory pattern. It is used to return one of
several factories.
 This pattern is one level of abstraction higher than factory pattern. This means that the
abstract factory returns the factory of classes. Like Factory pattern returned one of the
several sub-classes, this returns such factory which later will return one of the sub-
classes.
 Where to use & benefits
Creates families of related or dependent objects like Kit.
Provides a class library of products, exposing interface not implementation.
Needs to isolate concrete classes from their super classes.
A system needs independent of how its products are created, composed, and represented.
Try to enforce a constraint.
An alternative to Facade to hide platform-specific classes
Easily extensible to a system or a family
Related patterns include
 Factory method, which is often implemented with an abstract
factory.
 Singleton, which is often implemented with an abstract
factory.
 Prototype, which is often implemented with an abstract
factory.
 Facade, which is often used with an abstract factory by
providing an interface for creating implementing class.
example of Abstract factory patterns
 Suppose you need to write a program to show data in two
different places. Let's say from a local or a remote database.
You need to make a connection to a database before working on
the data. In this case, you have two choices, local or remote.
You may use abstract factory design pattern to design the
interface in the following way
class DataInfo {}
interface Local {
DataInfo[] loadDB(String filename);
}
interface Remote extends Local{
void connect2WWW(String url);
}
class LocalMode implements Local {
public DataInfo[] loadDB(String name) {
System.out.print("Load from a local database ");
return null;
}
}
class RemoteMode implements Remote {
public void connect2WWW(String url) {
System.out.println("Connect to a remote site ");
}
public DataInfo[] loadDB(String name) {
System.out.println("Load from a remote database ");
return null;
}
}
// The Abstract Factory
interface ConnectionFactory {
Local getLocalConnection();
Remote getRemoteConnection();
}
class DataManager implements ConnectionFactory {
boolean local = false;
DataInfo[] data;
//...
public Local getLocalConnection() {
return new LocalMode();
}
public Remote getRemoteConnection() {
return new RemoteMode();
}
public void loadData() {
if(local){
Local conn = getLocalConnection();
data = conn.loadDB("db.db");
}else {
Remote conn = getRemoteConnection();
conn.connect2WWW("www.some.where.com");
data = conn.loadDB("db.db");
}
}
// work on data
public void setConnection(boolean b) {
local = b;
}
}
//Use the following Test class to test the above classes
class Test {
public static void main(String[] args) {
DataManager dm = new DataManager();
DataInfo[] di = null;
String dbFileName = "db.db";
if (args.length == 1) {
//assume local is set to true
dm.setConnection(true);
LocalMode lm = (LocalMode)dm.getLocalConnection();
di = lm.loadDB(dbFileName);
} else {
//Note: dm.local = false is default setting
RemoteMode rm = (RemoteMode)dm.getRemoteConnection();
rm.connect2WWW("www.javacamp.org/db/");
di = rm.loadDB(dbFileName);
}
//use one set of methods to deal with loaded data.
//You don't need to worry about connection from this point.
//Like di.find(), di.search() etc.
}
}
Builder pattern
 Define Builder pattern
Construct a complex object from simple objects step by step.
 Builder, as the name suggests builds complex objects from simple ones step-by-
step. It separates the construction of complex objects from their
representation.
 Where to use & benefits
Make a complex object by specifying only its type and content. The built object
is shielded from the details of its construction.
Want to decouple the process of building a complex object from the parts that
make up the object.
Isolate code for construction and representation.
Give you finer control over the construction process.
Related patterns include
 Abstract Factory, which focuses on the layer over the factory
pattern (may be simple or complex), whereas a builder pattern
focuses on building a complex object from other simple
objects.
 Composite, which is often used to build a complex object.
example of Builder pattern
 To build a house, we will take several steps:
build foundation,
build frame,
build exterior,
build interior.
Let's use an abstract class HouseBuilder to define these 4 steps. Any
subclass of HouseBuilder will follow these 4 steps to build house
(that is to say to implement these 4 methods in the subclass). Then
we use a WorkShop class to force the order of these 4 steps (that is
to say that we have to build interior after having finished first three
steps). The TestBuilder class is used to test the coordination of
these classes and to check the building process.
mport java.util.*;
class WorkShop {
//force the order of building process
public void construct(HouseBuilder hb) {
hb.buildFoundation();
hb.buildFrame();
hb.buildExterior();
hb.buildInterior();
}
}
//set steps for building a house
abstract class HouseBuilder {
protected House house = new House();
protected String showProgress() {
return house.toString();
}
abstract public void buildFoundation();
abstract public void buildFrame();
abstract public void buildExterior();
abstract public void buildInterior();
}
class OneStoryHouse extends HouseBuilder {
public OneStoryHouse(String features) {
house.setType(this.getClass() + " " + features);
}
public void buildFoundation() {
//doEngineering()
//doExcavating()
//doPlumbingHeatingElectricity()
//doSewerWaterHookUp()
//doFoundationInspection()
house.setProgress("foundation is done");
}
public void buildFrame() {
//doHeatingPlumbingRoof()
//doElectricityRoute()
//doDoorsWindows()
//doFrameInspection()
house.setProgress("frame is done");
}
public void buildExterior() {
//doOverheadDoors()
//doBrickWorks()
//doSidingsoffitsGutters()
//doDrivewayGarageFloor()
//doDeckRail()
//doLandScaping()
house.setProgress("Exterior is done");
}
public void buildInterior() {
//doAlarmPrewiring()
//doBuiltinVacuum()
//doInsulation()
//doDryWall()
//doPainting()
//doLinoleum()
//doCabinet()
//doTileWork()
//doLightFixtureBlinds()
//doCleaning()
//doInteriorInspection()
house.setProgress("Interior is under going");
}
}
class TwoStoryHouse extends HouseBuilder {
public TwoStoryHouse(String features) {
house.setType(this.getClass() + " " + features);
}
public void buildFoundation() {
//doEngineering()
//doExcavating()
//doPlumbingHeatingElectricity()
//doSewerWaterHookUp()
//doFoundationInspection()
house.setProgress("foundation is done");
}
public void buildFrame() {
//doHeatingPlumbingRoof()
//doElectricityRoute()
//doDoorsWindows()
//doFrameInspection()
house.setProgress("frame is under construction");
}
public void buildExterior() {
//doOverheadDoors()
//doBrickWorks()
//doSidingsoffitsGutters()
//doDrivewayGarageFloor()
//doDeckRail()
//doLandScaping()
house.setProgress("Exterior is waiting to start");
}
public void buildInterior() {
//doAlarmPrewiring()
//doBuiltinVacuum()
//doInsulation()
//doDryWall()
//doPainting()
//doLinoleum()
//doCabinet()
//doTileWork()
//doLightFixtureBlinds()
//doCleaning()
//doInteriorInspection()
house.setProgress("Interior is not started yet");
}
}
 class House {
private String type = null;
private List features = new ArrayList();
public House() {
}
public House(String type) {
this.type = type;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setProgress(String s) {
features.add(s);
}
public String toString() {
StringBuffer ff = new StringBuffer();
String t = type.substring(6);
ff.append(t + "n ");
for (int i = 0; i < features.size(); i ++) {
ff.append(features.get(i) + "n ");
}
return ff.toString();
}
}
class TestBuilder {
public static void main(String[] args) {
HouseBuilder one = new OneStoryHouse("2 bedrooms, 2.5 baths, 2-car garage, 1500 sqft");
HouseBuilder two = new TwoStoryHouse("4 bedrooms, 4 baths, 3-car garage, 5000 sqft");
WorkShop shop = new WorkShop();
shop.construct(one);
shop.construct(two);
System.out.println("Check house building progress: n");
System.out.println(one.showProgress());
System.out.println(two.showProgress());
}
}
Factory Method Pattern
 Define factory method pattern
Provides an abstraction or an interface and lets subclass or implementing classes decide which
class or method should be instantiated or called, based on the conditions or parameters given.
 Factory of what? Of classes. In simple words, if we have a super class and n sub-classes, and
based on data provided, we have to return the object of one of the sub-classes, we use a
factory pattern.
 Where to use & benefits
Connect parallel class hierarchies.
A class wants its subclasses to specify the object.
A class cannot anticipate its subclasses, which must be created.
A family of objects needs to be separated by using shared interface.
The code needs to deal with interface, not implemented classes.
Hide concrete classes from the client.
Factory methods can be parameterized.
The returned object may be either abstract or concrete object.
Providing hooks for subclasses is more flexible than creating objects directly.
Follow naming conventions to help other developers to recognize the code structure.
Related patterns include
 Abstract Factory , which is a layer higher than a factory method.
 Template method, which defines a skeleton of an algorithm to
defer some steps to subclasses or avoid subclasses
 Prototype, which creates a new object by copying an instance,
so it reduces subclasses.
 Singleton, which makes a returned factory method unique.
Example of factory method pattern
 Examples
To illustrate such concept, let's use a simple example. To
paint a picture, you may need several steps. A shape is
an interface. Several implementing classes may be
designed in the following way.
 interface Shape {
public void draw();
}
class Line implements Shape {
Point x, y;
Line(Point a, Point b) {
x = a;
y = b;
}
public void draw() {
//draw a line;
}
}
class Square implements Shape {
Point start;
int width, height;
Square(Point s, int w, int h) {
start = s;
width = w;
height = h;
}
public void draw() {
//draw a square;
}
}
class Circle implements Shape {
....
}
class Painting {
Point x, y;
int width, height, radius;
Painting(Point a, Point b, int w, int h, int r) {
x = a;
y = b;
width = w;
height = h;
radius = r;
}
Shape drawLine() {
return new Line(x,y);
}
Shape drawSquare() {
return new Square(x, width, height);
}
Shape drawCircle() {
return new Circle(x, radius);
}
....
}
...
Shape pic;
Painting pt;
//initializing pt
....
if (line)
pic = pt.drawLine();
if (square)
pic = pt.drawSquare();
if (circle)
pic = pt.drawCircle();
 From the above example, you may see that the Shape pic's type depends on
the condition given. The variable pic may be a line or square or a circle.
--------------------------------------------------------------------------------
You may use several constructors with different parameters to instantiate
the object you want. It is another way to design with Factory pattern. For
example,
class Painting {
...
Painting(Point a, Point b) {
new Line(a, b); //draw a line
}
Painting(Point a, int w, int h) {
new Square(a, w, h); //draw a square
}
Painting(Point a, int r){
new Circle(a, r); //draw a circle
}
...
}
You may use several methods to finish the drawing jobs. It is so-called
factory method pattern. for example,
class Painting {
...
Painting(Point a, Point b) {
draw(a, b); //draw a line
}
Painting(Point a, int w, int h) {
draw(a, w, h); //draw a square
}
Painting(Point a, int r){
draw(a, r); //draw a circle
}
...
}
The above draw() methods are overloaded.
example
 Here is a popular example of Factory design pattern. For example,
you have several database storages located in several places. The
program working on the database is the same. The user may choose
local mode or remote mode. The condition is the choice by the
user. You may design your program with Factory pattern. When the
local mode is set, you may instantiate an object to work on the
local database. If the remote mode is set, you may instantiate an
object which may have more job to do like remote connection,
downloading, etc.
 interface DatabaseService {
public DataInfo getDataInfo() throws Exception;
public FieldInfo getFieldInfo() throws Exception;
public void write(FieldInfo fi) throws Exception;
public void modify(FieldInfo fi) throws Exception;
public void delete(FieldInfo fi) throws Exception;
//...
}
class Data implements DatabaseService {
public Data(String fileName) {...};
public Data(URL url, String fileName) {....};
public DataInfo getDataInfo() throws Exception {...};
public FieldInfo getFieldInfo() throws Exception {...};
public void write(FieldInfo fi) throws Exception {...};
public void modify(FieldInfo fi) throws Exception {...};
public void delete(FieldInfo fi) throws Exception {...};
//....
}
class DataManager{
Data data = null;
...
if (local) {
data = new Data(localFile);
...
}
if (remote){
data = new Data(connectRemote, databaseFile);
...
}
data.write(someInfo);
data.modify(someInfo);
....
}
 To illustrate how to use factory design pattern with class
level implementation, here is a real world example. A
company has a website to display testing result from a
plain text file. Recently, the company purchased a new
machine which produces a binary data file, another new
machine on the way, it is possible that one will produce
different data file. How to write a system to deal with such
change. The website just needs data to display. Your job is
to provide the specified data format for the website.
Here comes a solution. Use an interface type to converge
the different data file format. The following is a skeleton
of implementation.
 //Let's say the interface is Display
interface Display {
//load a file
public void load(String fileName);
//parse the file and make a consistent data type
public void formatConsistency();
}
//deal with plain text file
class CSVFile implements Display{
public void load(String textfile) {
System.out.println("load from a txt file");
}
public void formatConsistency() {
System.out.println("txt file format changed");
}
}
//deal with XML format file
class XMLFile implements Display {
public void load(String xmlfile) {
System.out.println("load from an xml file");
}
public void formatConsistency() {
System.out.println("xml file format changed");
}
}
//deal with binary format file
class DBFile implements Display {
public void load(String dbfile) {
System.out.println("load from a db file");
}
public void formatConsistency() {
System.out.println("db file format changed");
}
}
 //Test the functionality
class TestFactory {
public static void main(String[] args) {
Display display = null;
//use a command line data as a trigger
if (args[0].equals("1"))
display = new CSVFile();
else if (args[0].equals("2"))
display = new XMLFile();
else if (args[0].equals("3"))
display = new DBFile();
else
System.exit(1);
//converging code follows
display.load("");
display.formatConsistency();
}
}
//after compilation and run it
C:>java TestFactory 1
load from a txt file
txt file format changed
C:>java TestFactory 2
load from an xml file
xml file format changed
C:>java TestFactory 3
load from a db file
db file format changed
In the future, the company may add more data file with
different format, a programmer just adds a new class in
accordingly. Such design saves a lot of code and is easy to
maintain.
Prototype Pattern
Define Prototype pattern
 Cloning an object by reducing the cost of creation.
 The prototype means making a clone. This implies cloning of an object to avoid creation. If the
cost of creating a new object is large and creation is resource intensive, we clone the object. We
use the interface Cloneable and call its method clone() to clone the object.
 Where to use & benefits
When there are many subclasses that differ only in the kind of objects,
A system needs independent of how its objects are created, composed, and represented.
Dynamic binding or loading a method.
Use one instance to finish job just by changing its state or parameters.
Add and remove objects at runtime.
Specify new objects by changing its structure.
Configure an application with classes dynamically.
Related patterns include
 Abstract Factory, which is often used together with prototype.
An abstract factory may store some prototypes for cloning and
returning objects.
 Composite, which is often used with prototypes to make a part-
whole relationship.
 Decorator, which is used to add additional functionality to the
prototype.
Example of prototype pattern
 Dynamic loading is a typical object-oriented feature and
prototype example. For example, overriding method is a
kind of prototype pattern.
 interface Shape {
public void draw();
}
class Line implements Shape {
public void draw() {
System.out.println("line");
}
}
class Square implements Shape {
public void draw() {
System.out.println("square");
}
}
class Circle implements Shape {
public void draw() {
System.out.println("circle");
}
}
class Painting {
public static void main(String[] args) {
Shape s1 = new Line();
Shape s2 = new Square();
Shape s3 = new Circle();
paint(s1);
paint(s2);
paint(s3);
}
static void paint(Shape s) {
if ( s instanceof Line)
s.draw();
if (s instanceof Square)
s.draw();
if (s instanceof Circle)
s.draw();
}
}
Out put is :
line
square
circle
The paint method takes a variable of Shape type at runtime. The draw
method is called based on the runtime type.
Overloading method is a kind of prototype too.
class Painting {
public void draw(Point p, Point p2) {
//draw a line
}
public void draw(Point p, int x, int y) {
//draw a square
}
public void draw(Point p, int x) {
//draw a circle
}
}
 static Complex c1 = new Complex();
static Complex makeCopy() {
return (Complex)c1.clone();
}
public static void main(String[] args) {
Complex c1 = makeCopy();
int[] mycopy = c1.getNums();
for(int i = 0; i < mycopy.length; i++)
System.out.print(mycopy[i]);
}
}
Outpput is :
12345
Cloning is a shallow copy of the original object. If the cloned object has
been changed, the original object will be changed accordingly. See the
following alteration.
class Complex implements Cloneable {
int[] nums = {1,2,3,4,5};
public Object clone() {
try {
return super.clone();
}catch(CloneNotSupportedException cnse) {
System.out.println(cnse.getMessage());
return null;
}
}
int[] getNums() {
return nums;
}
}
class Test {
Complex c1 = new Complex();
Complex makeCopy() {
return (Complex)c1.clone();
}
public static void main(String[] args) {
Test tp = new Test();
Complex c2 = tp.makeCopy();
int[] mycopy = c2.getNums();
mycopy[0] = 5;
System.out.println();
System.out.print("local array: ");
for(int i = 0; i < mycopy.length; i++)
System.out.print(mycopy[i]);
System.out.println();
System.out.print("cloned object: ");
for(int ii = 0; ii < c2.nums.length; ii++)
System.out.print(c2.nums[ii]);
System.out.println();
System.out.print("original object: ");
for(int iii = 0; iii < tp.c1.nums.length; iii++)
System.out.print(tp.c1.nums[iii]);
}
 Output is :
local array: 52345
cloned object: 52345
original object: 52345
To avoid such side effect, you may use a deep copy instead of a
shallow copy. The following shows the alteration to the above
example, note that the Complex class doesn't implement Cloneable
interface.
class Complex {
int[] nums = {1,2,3,4,5};
public Complex clone() {
return new Complex();
}
int[] getNums() {
return nums;
}
}
class Test2 {
Complex c1 = new Complex();
Complex makeCopy() {
return (Complex)c1.clone();
}
public static void main(String[] args) {
Test2 tp = new Test2();
Complex c2 = tp.makeCopy();
int[] mycopy = c2.getNums();
mycopy[0] = 5;
System.out.println();
System.out.print("local array: ");
for(int i = 0; i < mycopy.length; i++)
System.out.print(mycopy[i]);
System.out.println();
System.out.print("cloned object: ");
for(int ii = 0; ii < c2.nums.length; ii++)
System.out.print(c2.nums[ii]);
System.out.println();
System.out.print("original object: ");
for(int iii = 0; iii < tp.c1.nums.length; iii++)
System.out.print(tp.c1.nums[iii]);
}
}
 Output :
local array: 52345
cloned object: 52345
original object: 12345
Singleton Pattern
 Define Singleton pattern
One instance of a class or one value accessible globally in an
application.
Where to use & benefits
Ensure unique instance by defining class final to prevent cloning.
May be extensible by the subclass by defining subclass final.
Make a method or a variable public or/and static.
Access to the instance by the way you provided.
Well control the instantiation of a class.
Define one value shared by all instances by making it static.
Related patterns include
 Abstract factory, which is often used to return unique
objects.
 Builder, which is used to construct a complex object,
whereas a singleton is used to create a globally
accessible object.
 Prototype, which is used to copy an object, or create
an object from its prototype, whereas a singleton is
used to ensure that only one prototype is guaranteed.
Example of Singleton Pattern
 One file system, one window manager, one printer spooler, one
Test engine, one Input/Output socket and etc.
To design a Singleton class, you may need to make the class
final like java.Math, which is not allowed to subclass, or make a
variable or method public and/or static, or make all
constructors private to prevent the compiler from creating a
default one.
For example, to make a unique remote connection,
 final class RemoteConnection {
private Connect con;
private static RemoteConnection rc = new
RemoteConnection(connection);
private RemoteConnection(Connect c) {
con = c;
....
}
public static RemoteConnection getRemoteConnection() {
return rc;
}
public void setConnection(Connect c) {
this(c);
}
}
usage:
RemoteConnection rconn = RemoteConnection.getRemoteConnection;
rconn.loadData();
...
The following statement may fail because of the private constructor
RemoteConnection con = new RemoteConnection(connection); //failed
//failed because you cannot subclass it (final class)
class Connection extends RemoteConnection {}
For example, to use a static variable to control the instance;
class Connection {
public static boolean haveOne = false;
public Connection() throws Exception{
if (!haveOne) {
doSomething();
haveOne = true;
}else {
throw new Exception("You cannot have a second instance");
}
}
public static Connection getConnection() throws Exception{
return new Connection();
}
void doSomething() {}
//...
public static void main(String [] args) {
try {
Connection con = new Connection(); //ok
}catch(Exception e) {
System.out.println("first: " +e.getMessage());
}
try {
Connection con2 = Connection.getConnection(); //failed.
}catch(Exception e) {
System.out.println("second: " +e.getMessage());
}
}
}
 C: Command Prompt
C:> java Connection
second: You cannot have a second instance
For example to use a public static variable to ensure a unique.
class Employee {
public static final int companyID = 12345;
public String address;
//...
}
class HourlyEmployee extends Employee {
public double hourlyRate;
//....
}
class SalaryEmployee extends Employee {
public double salary;
//...
}
class Test {
public static void main(String[] args) {
Employee Evens = new Employee();
HourlyEmployee Hellen = new HourlyEmployee();
SalaryEmployee Sara = new SalaryEmployee();
System.out.println(Evens.companyID == Hellen.companyID); //true
System.out.println(Evens.companyID == Sara.companyID); //true
}
}
Output :
true
true
The companyID is a unique and cannot be altered by all subclasses.
Note that Singletons are only guaranteed to be unique within a given class
loader. If you use the same class across multiple distinct enterprise
containers, you'll get one instance for each container.
Creational pattern 2
Creational pattern 2

More Related Content

PPTX
Structural pattern 3
PDF
C# Advanced L07-Design Patterns
PDF
OpenDMS - the first 2 weeks
PPT
Software Design Patterns
PDF
Design patterns in Java - Monitis 2017
PPT
Web based development
ODP
EJB 3.0 Walkthrough (2006)
DOC
Advanced core java
Structural pattern 3
C# Advanced L07-Design Patterns
OpenDMS - the first 2 weeks
Software Design Patterns
Design patterns in Java - Monitis 2017
Web based development
EJB 3.0 Walkthrough (2006)
Advanced core java

What's hot (20)

ODT
Types of Dependency Injection in Spring
DOCX
Introduction to object oriented programming concepts
PPTX
Java Beans
PDF
Java Programming - 08 java threading
PDF
Bt0083 server side programing 2
PPTX
Entity Framework: Nakov @ BFU Hackhaton 2015
PPTX
Interface java
PDF
S313937 cdi dochez
PPT
Java jdbc
PDF
java-06inheritance
PDF
Hacking XPATH 2.0
PPTX
XML & XPath Injections
PPTX
Design Patterns - Part 1 of 2
PPT
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
PPT
Chapter 4 - Defining Your Own Classes - Part I
PPTX
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
PPT
XPath Injection
PPTX
Design Patterns - Part 2 of 2
Types of Dependency Injection in Spring
Introduction to object oriented programming concepts
Java Beans
Java Programming - 08 java threading
Bt0083 server side programing 2
Entity Framework: Nakov @ BFU Hackhaton 2015
Interface java
S313937 cdi dochez
Java jdbc
java-06inheritance
Hacking XPATH 2.0
XML & XPath Injections
Design Patterns - Part 1 of 2
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Chapter 4 - Defining Your Own Classes - Part I
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
XPath Injection
Design Patterns - Part 2 of 2
Ad

Similar to Creational pattern 2 (20)

PPTX
Gof design patterns
PPT
Unit 2-Design Patterns.ppt
DOCX
Abstract factory
PPTX
Code Like a Ninja Session 7 - Creational Design Patterns
PPTX
Creational Design Patterns.pptx
PPTX
design patter related ppt and presentation
PPTX
Design patterns(red)
PPT
PPTX
PPTX
Creational Patterns
PPTX
PATTERNS02 - Creational Design Patterns
PPT
Introduction to design_patterns
PPT
Design Patterns
PPTX
Design Pattern - Factory Method Pattern
PPTX
CREATIONAL Pattern .pptx
PPTX
Design patterns
PPTX
Software Architecture and Design Patterns Notes.pptx
PPTX
Cs 1023 lec 8 design pattern (week 2)
PDF
Why Design Patterns Are Important In Software Engineering
DOCX
Java Design Pattern Interview Questions
Gof design patterns
Unit 2-Design Patterns.ppt
Abstract factory
Code Like a Ninja Session 7 - Creational Design Patterns
Creational Design Patterns.pptx
design patter related ppt and presentation
Design patterns(red)
Creational Patterns
PATTERNS02 - Creational Design Patterns
Introduction to design_patterns
Design Patterns
Design Pattern - Factory Method Pattern
CREATIONAL Pattern .pptx
Design patterns
Software Architecture and Design Patterns Notes.pptx
Cs 1023 lec 8 design pattern (week 2)
Why Design Patterns Are Important In Software Engineering
Java Design Pattern Interview Questions
Ad

More from Naga Muruga (20)

PDF
Naga Muruga (1.6 Years) Developer Resume
PDF
CHAITANYA UNIVERSITY - BEST POSTER.pdf
PDF
AMET - BEST PRESENTATION.pdf
PDF
Intro to Git
PDF
DEvOpS, CI/CD For Beginners.pdf
PDF
API and Web Service Introduction .pdf
PDF
Naga muruga resume
PPTX
Self Healing Materials - A Review
PDF
Fundamentals of Manuscript Preparation
PDF
Auto CAD (Beginner)
PDF
Content Writing
PDF
Boilers, Types and Energy Efficiency
PDF
Project Management Essentials
PDF
Lean Six Sigma White Belt
PDF
Basics of Drives and Motors
PDF
Supply Chain
PPTX
Green walls
PPTX
Anti juice jacking smart solar charger
PDF
Top 32 technologies
PDF
Controversy on feminism
Naga Muruga (1.6 Years) Developer Resume
CHAITANYA UNIVERSITY - BEST POSTER.pdf
AMET - BEST PRESENTATION.pdf
Intro to Git
DEvOpS, CI/CD For Beginners.pdf
API and Web Service Introduction .pdf
Naga muruga resume
Self Healing Materials - A Review
Fundamentals of Manuscript Preparation
Auto CAD (Beginner)
Content Writing
Boilers, Types and Energy Efficiency
Project Management Essentials
Lean Six Sigma White Belt
Basics of Drives and Motors
Supply Chain
Green walls
Anti juice jacking smart solar charger
Top 32 technologies
Controversy on feminism

Recently uploaded (20)

PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
Digital Logic Computer Design lecture notes
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Model Code of Practice - Construction Work - 21102022 .pdf
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
UNIT 4 Total Quality Management .pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
OOP with Java - Java Introduction (Basics)
Foundation to blockchain - A guide to Blockchain Tech
CYBER-CRIMES AND SECURITY A guide to understanding
Operating System & Kernel Study Guide-1 - converted.pdf
Digital Logic Computer Design lecture notes
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Lecture Notes Electrical Wiring System Components
UNIT-1 - COAL BASED THERMAL POWER PLANTS
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd

Creational pattern 2

  • 1. Creational Pattern - 2 By, D. B. Naga Muruga, Dept of Mechanical Engineering, Sriram Engineering College
  • 2. Abstract factory Pattern  Define abstract factory pattern Definition Provides one level of interface higher than the factory pattern. It is used to return one of several factories.  This pattern is one level of abstraction higher than factory pattern. This means that the abstract factory returns the factory of classes. Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the sub- classes.  Where to use & benefits Creates families of related or dependent objects like Kit. Provides a class library of products, exposing interface not implementation. Needs to isolate concrete classes from their super classes. A system needs independent of how its products are created, composed, and represented. Try to enforce a constraint. An alternative to Facade to hide platform-specific classes Easily extensible to a system or a family
  • 3. Related patterns include  Factory method, which is often implemented with an abstract factory.  Singleton, which is often implemented with an abstract factory.  Prototype, which is often implemented with an abstract factory.  Facade, which is often used with an abstract factory by providing an interface for creating implementing class.
  • 4. example of Abstract factory patterns  Suppose you need to write a program to show data in two different places. Let's say from a local or a remote database. You need to make a connection to a database before working on the data. In this case, you have two choices, local or remote. You may use abstract factory design pattern to design the interface in the following way
  • 5. class DataInfo {} interface Local { DataInfo[] loadDB(String filename); } interface Remote extends Local{ void connect2WWW(String url); } class LocalMode implements Local { public DataInfo[] loadDB(String name) { System.out.print("Load from a local database "); return null; } } class RemoteMode implements Remote { public void connect2WWW(String url) { System.out.println("Connect to a remote site "); } public DataInfo[] loadDB(String name) { System.out.println("Load from a remote database "); return null; } } // The Abstract Factory interface ConnectionFactory { Local getLocalConnection(); Remote getRemoteConnection(); } class DataManager implements ConnectionFactory { boolean local = false; DataInfo[] data; //... public Local getLocalConnection() { return new LocalMode(); } public Remote getRemoteConnection() { return new RemoteMode(); } public void loadData() { if(local){ Local conn = getLocalConnection(); data = conn.loadDB("db.db"); }else { Remote conn = getRemoteConnection(); conn.connect2WWW("www.some.where.com"); data = conn.loadDB("db.db"); } } // work on data public void setConnection(boolean b) { local = b; } } //Use the following Test class to test the above classes class Test { public static void main(String[] args) { DataManager dm = new DataManager(); DataInfo[] di = null; String dbFileName = "db.db"; if (args.length == 1) { //assume local is set to true dm.setConnection(true); LocalMode lm = (LocalMode)dm.getLocalConnection(); di = lm.loadDB(dbFileName); } else { //Note: dm.local = false is default setting RemoteMode rm = (RemoteMode)dm.getRemoteConnection(); rm.connect2WWW("www.javacamp.org/db/"); di = rm.loadDB(dbFileName); } //use one set of methods to deal with loaded data. //You don't need to worry about connection from this point. //Like di.find(), di.search() etc. } }
  • 6. Builder pattern  Define Builder pattern Construct a complex object from simple objects step by step.  Builder, as the name suggests builds complex objects from simple ones step-by- step. It separates the construction of complex objects from their representation.  Where to use & benefits Make a complex object by specifying only its type and content. The built object is shielded from the details of its construction. Want to decouple the process of building a complex object from the parts that make up the object. Isolate code for construction and representation. Give you finer control over the construction process.
  • 7. Related patterns include  Abstract Factory, which focuses on the layer over the factory pattern (may be simple or complex), whereas a builder pattern focuses on building a complex object from other simple objects.  Composite, which is often used to build a complex object.
  • 8. example of Builder pattern  To build a house, we will take several steps: build foundation, build frame, build exterior, build interior. Let's use an abstract class HouseBuilder to define these 4 steps. Any subclass of HouseBuilder will follow these 4 steps to build house (that is to say to implement these 4 methods in the subclass). Then we use a WorkShop class to force the order of these 4 steps (that is to say that we have to build interior after having finished first three steps). The TestBuilder class is used to test the coordination of these classes and to check the building process.
  • 9. mport java.util.*; class WorkShop { //force the order of building process public void construct(HouseBuilder hb) { hb.buildFoundation(); hb.buildFrame(); hb.buildExterior(); hb.buildInterior(); } } //set steps for building a house abstract class HouseBuilder { protected House house = new House(); protected String showProgress() { return house.toString(); } abstract public void buildFoundation(); abstract public void buildFrame(); abstract public void buildExterior(); abstract public void buildInterior(); } class OneStoryHouse extends HouseBuilder { public OneStoryHouse(String features) { house.setType(this.getClass() + " " + features); } public void buildFoundation() { //doEngineering() //doExcavating() //doPlumbingHeatingElectricity() //doSewerWaterHookUp() //doFoundationInspection() house.setProgress("foundation is done"); } public void buildFrame() { //doHeatingPlumbingRoof() //doElectricityRoute() //doDoorsWindows() //doFrameInspection() house.setProgress("frame is done"); } public void buildExterior() { //doOverheadDoors() //doBrickWorks() //doSidingsoffitsGutters() //doDrivewayGarageFloor() //doDeckRail() //doLandScaping() house.setProgress("Exterior is done"); } public void buildInterior() { //doAlarmPrewiring() //doBuiltinVacuum() //doInsulation() //doDryWall() //doPainting() //doLinoleum() //doCabinet() //doTileWork() //doLightFixtureBlinds() //doCleaning() //doInteriorInspection() house.setProgress("Interior is under going"); } } class TwoStoryHouse extends HouseBuilder { public TwoStoryHouse(String features) { house.setType(this.getClass() + " " + features); } public void buildFoundation() { //doEngineering() //doExcavating() //doPlumbingHeatingElectricity() //doSewerWaterHookUp() //doFoundationInspection() house.setProgress("foundation is done"); } public void buildFrame() { //doHeatingPlumbingRoof() //doElectricityRoute() //doDoorsWindows() //doFrameInspection() house.setProgress("frame is under construction"); } public void buildExterior() { //doOverheadDoors() //doBrickWorks() //doSidingsoffitsGutters() //doDrivewayGarageFloor() //doDeckRail() //doLandScaping() house.setProgress("Exterior is waiting to start"); } public void buildInterior() { //doAlarmPrewiring() //doBuiltinVacuum() //doInsulation() //doDryWall() //doPainting() //doLinoleum() //doCabinet() //doTileWork() //doLightFixtureBlinds() //doCleaning() //doInteriorInspection() house.setProgress("Interior is not started yet"); } }
  • 10.  class House { private String type = null; private List features = new ArrayList(); public House() { } public House(String type) { this.type = type; } public void setType(String type) { this.type = type; } public String getType() { return type; } public void setProgress(String s) { features.add(s); } public String toString() { StringBuffer ff = new StringBuffer(); String t = type.substring(6); ff.append(t + "n "); for (int i = 0; i < features.size(); i ++) { ff.append(features.get(i) + "n "); } return ff.toString(); } } class TestBuilder { public static void main(String[] args) { HouseBuilder one = new OneStoryHouse("2 bedrooms, 2.5 baths, 2-car garage, 1500 sqft"); HouseBuilder two = new TwoStoryHouse("4 bedrooms, 4 baths, 3-car garage, 5000 sqft"); WorkShop shop = new WorkShop(); shop.construct(one); shop.construct(two); System.out.println("Check house building progress: n"); System.out.println(one.showProgress()); System.out.println(two.showProgress()); } }
  • 11. Factory Method Pattern  Define factory method pattern Provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated or called, based on the conditions or parameters given.  Factory of what? Of classes. In simple words, if we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.  Where to use & benefits Connect parallel class hierarchies. A class wants its subclasses to specify the object. A class cannot anticipate its subclasses, which must be created. A family of objects needs to be separated by using shared interface. The code needs to deal with interface, not implemented classes. Hide concrete classes from the client. Factory methods can be parameterized. The returned object may be either abstract or concrete object. Providing hooks for subclasses is more flexible than creating objects directly. Follow naming conventions to help other developers to recognize the code structure.
  • 12. Related patterns include  Abstract Factory , which is a layer higher than a factory method.  Template method, which defines a skeleton of an algorithm to defer some steps to subclasses or avoid subclasses  Prototype, which creates a new object by copying an instance, so it reduces subclasses.  Singleton, which makes a returned factory method unique.
  • 13. Example of factory method pattern  Examples To illustrate such concept, let's use a simple example. To paint a picture, you may need several steps. A shape is an interface. Several implementing classes may be designed in the following way.
  • 14.  interface Shape { public void draw(); } class Line implements Shape { Point x, y; Line(Point a, Point b) { x = a; y = b; } public void draw() { //draw a line; } } class Square implements Shape { Point start; int width, height; Square(Point s, int w, int h) { start = s; width = w; height = h; } public void draw() { //draw a square; } } class Circle implements Shape { .... } class Painting { Point x, y; int width, height, radius; Painting(Point a, Point b, int w, int h, int r) { x = a; y = b; width = w; height = h; radius = r; } Shape drawLine() { return new Line(x,y); } Shape drawSquare() { return new Square(x, width, height); } Shape drawCircle() { return new Circle(x, radius); } .... } ... Shape pic; Painting pt; //initializing pt .... if (line) pic = pt.drawLine(); if (square) pic = pt.drawSquare(); if (circle) pic = pt.drawCircle();  From the above example, you may see that the Shape pic's type depends on the condition given. The variable pic may be a line or square or a circle. -------------------------------------------------------------------------------- You may use several constructors with different parameters to instantiate the object you want. It is another way to design with Factory pattern. For example, class Painting { ... Painting(Point a, Point b) { new Line(a, b); //draw a line } Painting(Point a, int w, int h) { new Square(a, w, h); //draw a square } Painting(Point a, int r){ new Circle(a, r); //draw a circle } ... } You may use several methods to finish the drawing jobs. It is so-called factory method pattern. for example, class Painting { ... Painting(Point a, Point b) { draw(a, b); //draw a line } Painting(Point a, int w, int h) { draw(a, w, h); //draw a square } Painting(Point a, int r){ draw(a, r); //draw a circle } ... } The above draw() methods are overloaded.
  • 15. example  Here is a popular example of Factory design pattern. For example, you have several database storages located in several places. The program working on the database is the same. The user may choose local mode or remote mode. The condition is the choice by the user. You may design your program with Factory pattern. When the local mode is set, you may instantiate an object to work on the local database. If the remote mode is set, you may instantiate an object which may have more job to do like remote connection, downloading, etc.
  • 16.  interface DatabaseService { public DataInfo getDataInfo() throws Exception; public FieldInfo getFieldInfo() throws Exception; public void write(FieldInfo fi) throws Exception; public void modify(FieldInfo fi) throws Exception; public void delete(FieldInfo fi) throws Exception; //... } class Data implements DatabaseService { public Data(String fileName) {...}; public Data(URL url, String fileName) {....}; public DataInfo getDataInfo() throws Exception {...}; public FieldInfo getFieldInfo() throws Exception {...}; public void write(FieldInfo fi) throws Exception {...}; public void modify(FieldInfo fi) throws Exception {...}; public void delete(FieldInfo fi) throws Exception {...}; //.... } class DataManager{ Data data = null; ... if (local) { data = new Data(localFile); ... } if (remote){ data = new Data(connectRemote, databaseFile); ... } data.write(someInfo); data.modify(someInfo); .... }
  • 17.  To illustrate how to use factory design pattern with class level implementation, here is a real world example. A company has a website to display testing result from a plain text file. Recently, the company purchased a new machine which produces a binary data file, another new machine on the way, it is possible that one will produce different data file. How to write a system to deal with such change. The website just needs data to display. Your job is to provide the specified data format for the website. Here comes a solution. Use an interface type to converge the different data file format. The following is a skeleton of implementation.
  • 18.  //Let's say the interface is Display interface Display { //load a file public void load(String fileName); //parse the file and make a consistent data type public void formatConsistency(); } //deal with plain text file class CSVFile implements Display{ public void load(String textfile) { System.out.println("load from a txt file"); } public void formatConsistency() { System.out.println("txt file format changed"); } } //deal with XML format file class XMLFile implements Display { public void load(String xmlfile) { System.out.println("load from an xml file"); } public void formatConsistency() { System.out.println("xml file format changed"); } } //deal with binary format file class DBFile implements Display { public void load(String dbfile) { System.out.println("load from a db file"); } public void formatConsistency() { System.out.println("db file format changed"); } }  //Test the functionality class TestFactory { public static void main(String[] args) { Display display = null; //use a command line data as a trigger if (args[0].equals("1")) display = new CSVFile(); else if (args[0].equals("2")) display = new XMLFile(); else if (args[0].equals("3")) display = new DBFile(); else System.exit(1); //converging code follows display.load(""); display.formatConsistency(); } } //after compilation and run it C:>java TestFactory 1 load from a txt file txt file format changed C:>java TestFactory 2 load from an xml file xml file format changed C:>java TestFactory 3 load from a db file db file format changed In the future, the company may add more data file with different format, a programmer just adds a new class in accordingly. Such design saves a lot of code and is easy to maintain.
  • 19. Prototype Pattern Define Prototype pattern  Cloning an object by reducing the cost of creation.  The prototype means making a clone. This implies cloning of an object to avoid creation. If the cost of creating a new object is large and creation is resource intensive, we clone the object. We use the interface Cloneable and call its method clone() to clone the object.  Where to use & benefits When there are many subclasses that differ only in the kind of objects, A system needs independent of how its objects are created, composed, and represented. Dynamic binding or loading a method. Use one instance to finish job just by changing its state or parameters. Add and remove objects at runtime. Specify new objects by changing its structure. Configure an application with classes dynamically.
  • 20. Related patterns include  Abstract Factory, which is often used together with prototype. An abstract factory may store some prototypes for cloning and returning objects.  Composite, which is often used with prototypes to make a part- whole relationship.  Decorator, which is used to add additional functionality to the prototype.
  • 21. Example of prototype pattern  Dynamic loading is a typical object-oriented feature and prototype example. For example, overriding method is a kind of prototype pattern.
  • 22.  interface Shape { public void draw(); } class Line implements Shape { public void draw() { System.out.println("line"); } } class Square implements Shape { public void draw() { System.out.println("square"); } } class Circle implements Shape { public void draw() { System.out.println("circle"); } } class Painting { public static void main(String[] args) { Shape s1 = new Line(); Shape s2 = new Square(); Shape s3 = new Circle(); paint(s1); paint(s2); paint(s3); } static void paint(Shape s) { if ( s instanceof Line) s.draw(); if (s instanceof Square) s.draw(); if (s instanceof Circle) s.draw(); } } Out put is : line square circle The paint method takes a variable of Shape type at runtime. The draw method is called based on the runtime type. Overloading method is a kind of prototype too. class Painting { public void draw(Point p, Point p2) { //draw a line } public void draw(Point p, int x, int y) { //draw a square } public void draw(Point p, int x) { //draw a circle } }  static Complex c1 = new Complex(); static Complex makeCopy() { return (Complex)c1.clone(); } public static void main(String[] args) { Complex c1 = makeCopy(); int[] mycopy = c1.getNums(); for(int i = 0; i < mycopy.length; i++) System.out.print(mycopy[i]); } } Outpput is : 12345 Cloning is a shallow copy of the original object. If the cloned object has been changed, the original object will be changed accordingly. See the following alteration. class Complex implements Cloneable { int[] nums = {1,2,3,4,5}; public Object clone() { try { return super.clone(); }catch(CloneNotSupportedException cnse) { System.out.println(cnse.getMessage()); return null; } } int[] getNums() { return nums; } } class Test { Complex c1 = new Complex(); Complex makeCopy() { return (Complex)c1.clone(); } public static void main(String[] args) { Test tp = new Test(); Complex c2 = tp.makeCopy(); int[] mycopy = c2.getNums(); mycopy[0] = 5; System.out.println(); System.out.print("local array: "); for(int i = 0; i < mycopy.length; i++) System.out.print(mycopy[i]); System.out.println(); System.out.print("cloned object: "); for(int ii = 0; ii < c2.nums.length; ii++) System.out.print(c2.nums[ii]); System.out.println(); System.out.print("original object: "); for(int iii = 0; iii < tp.c1.nums.length; iii++) System.out.print(tp.c1.nums[iii]); }
  • 23.  Output is : local array: 52345 cloned object: 52345 original object: 52345 To avoid such side effect, you may use a deep copy instead of a shallow copy. The following shows the alteration to the above example, note that the Complex class doesn't implement Cloneable interface. class Complex { int[] nums = {1,2,3,4,5}; public Complex clone() { return new Complex(); } int[] getNums() { return nums; } } class Test2 { Complex c1 = new Complex(); Complex makeCopy() { return (Complex)c1.clone(); } public static void main(String[] args) { Test2 tp = new Test2(); Complex c2 = tp.makeCopy(); int[] mycopy = c2.getNums(); mycopy[0] = 5; System.out.println(); System.out.print("local array: "); for(int i = 0; i < mycopy.length; i++) System.out.print(mycopy[i]); System.out.println(); System.out.print("cloned object: "); for(int ii = 0; ii < c2.nums.length; ii++) System.out.print(c2.nums[ii]); System.out.println(); System.out.print("original object: "); for(int iii = 0; iii < tp.c1.nums.length; iii++) System.out.print(tp.c1.nums[iii]); } }  Output : local array: 52345 cloned object: 52345 original object: 12345
  • 24. Singleton Pattern  Define Singleton pattern One instance of a class or one value accessible globally in an application. Where to use & benefits Ensure unique instance by defining class final to prevent cloning. May be extensible by the subclass by defining subclass final. Make a method or a variable public or/and static. Access to the instance by the way you provided. Well control the instantiation of a class. Define one value shared by all instances by making it static.
  • 25. Related patterns include  Abstract factory, which is often used to return unique objects.  Builder, which is used to construct a complex object, whereas a singleton is used to create a globally accessible object.  Prototype, which is used to copy an object, or create an object from its prototype, whereas a singleton is used to ensure that only one prototype is guaranteed.
  • 26. Example of Singleton Pattern  One file system, one window manager, one printer spooler, one Test engine, one Input/Output socket and etc. To design a Singleton class, you may need to make the class final like java.Math, which is not allowed to subclass, or make a variable or method public and/or static, or make all constructors private to prevent the compiler from creating a default one. For example, to make a unique remote connection,
  • 27.  final class RemoteConnection { private Connect con; private static RemoteConnection rc = new RemoteConnection(connection); private RemoteConnection(Connect c) { con = c; .... } public static RemoteConnection getRemoteConnection() { return rc; } public void setConnection(Connect c) { this(c); } } usage: RemoteConnection rconn = RemoteConnection.getRemoteConnection; rconn.loadData(); ... The following statement may fail because of the private constructor RemoteConnection con = new RemoteConnection(connection); //failed //failed because you cannot subclass it (final class) class Connection extends RemoteConnection {} For example, to use a static variable to control the instance; class Connection { public static boolean haveOne = false; public Connection() throws Exception{ if (!haveOne) { doSomething(); haveOne = true; }else { throw new Exception("You cannot have a second instance"); } } public static Connection getConnection() throws Exception{ return new Connection(); } void doSomething() {} //... public static void main(String [] args) { try { Connection con = new Connection(); //ok }catch(Exception e) { System.out.println("first: " +e.getMessage()); } try { Connection con2 = Connection.getConnection(); //failed. }catch(Exception e) { System.out.println("second: " +e.getMessage()); } } }  C: Command Prompt C:> java Connection second: You cannot have a second instance For example to use a public static variable to ensure a unique. class Employee { public static final int companyID = 12345; public String address; //... } class HourlyEmployee extends Employee { public double hourlyRate; //.... } class SalaryEmployee extends Employee { public double salary; //... } class Test { public static void main(String[] args) { Employee Evens = new Employee(); HourlyEmployee Hellen = new HourlyEmployee(); SalaryEmployee Sara = new SalaryEmployee(); System.out.println(Evens.companyID == Hellen.companyID); //true System.out.println(Evens.companyID == Sara.companyID); //true } } Output : true true The companyID is a unique and cannot be altered by all subclasses. Note that Singletons are only guaranteed to be unique within a given class loader. If you use the same class across multiple distinct enterprise containers, you'll get one instance for each container.