SlideShare a Scribd company logo
Structural Pattern - 3
By,
D. B. Naga Muruga,
Dept of Mechanical Engineering,
Sriram Engineering College
Adapter Pattern
Define Adapter pattern
 Convert the existing interfaces to a new interface to achieve compatibility and reusability of the unrelated classes in
one application. Also known as Wrapper pattern.
 The Adapter pattern is used so that two unrelated interfaces can work together. The joining between them is called an
Adapter. This is something like we convert interface of one class into interface expected by the client. We do that using
an Adapter.
 Where to use & benefits
Try to match an interface(WindowAdapter, etc.)
Make unrelated classes work together.
Multiple compatibility.
Increase transparency of classes.
Make a pluggable kit.
Delegate objects.
Highly class reusable.
Achieve the goal by inheritance or by composition
Related patterns include
Proxy, which provides the same interface as its subject, whereas an adapter provides a different interface to the object
it adapts.
Decorator, which focuses on adding new functions to an object, whereas an adapter coordinates two different objects.
Bridge, which tries to separate an interface from its implementation and make an object vary independently, whereas
an adapter tries to change and cooperate the interface of an object.
Example of Adapter pattern
 The famous adapter classes in Java API are
WindowAdapter,ComponentAdapter, ContainerAdapter, FocusAdapter,
KeyAdapter, MouseAdapter and MouseMotionAdapter.
As you know, WindowListner interface has seven methods. Whenever
your class implements such interface, you have to implements all of
the seven methods. WindowAdapter class implements WindowListener
interface and make seven empty implementation. When you class
subclass WindowAdapter class, you may choose the method you want
without restrictions. The following give such an example.
 public interface Windowlistener {
public void windowClosed(WindowEvent e);
public void windowOpened(WindowEvent e);
public void windowIconified(WindowEvent e);
public void windowDeiconified(WindowEvent e);
public void windowActivated(WindowEvent e);
public void windowDeactivated(WindowEvent e);
public void windowClosing(WindowEvent e);
}
public class WindowAdapter implements WindowListner{
public void windowClosed(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowClosing(WindowEvent e){}
}
Here is a test program
import javax.swing.*;
import java.awt.event.*;
class Test extends JFrame {
public Test () {
setSize(200,200);
setVisible(true);
addWindowListener(new Closer());
}
public static void main(String[] args) {
new Test();
}
class Closer extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}
To reuse classes and make new class compatible with existing ones. For
example, A clean system is already designed, you want to add more job in,
the Extra interface uses adapter pattern to plug in the existing system.
interface Clean {
public void makeClean();
}
class Office implements Clean{
public void makeClean() {
System.out.println("Clean Office");
}
}
class Workshop implements Clean{
public void makeClean() {
System.out.println("Clean Workshop");
}
}
interface Extra extends Clean{
public void takeCare();
}
class Facility implements Extra{
public void makeClean() {
System.out.println("Clean Facility");
}
 public void takeCare() {
System.out.println("Care has been taken");
}
}
 In order to reuse Workshop and Office classes,
we create an adapter interface Extra and
add new job takeCare in the system.
class Test {
static void Jobs (Extra job) {
if (job instanceof Clean)
((Clean)job).makeClean();
if ((Extra)job instanceof Extra)
((Extra)job).takeCare();
}
public static void main(String[] args) {
Extra e = new Facility();
Jobs(e);
Clean c1 = new Office();
Clean c2 = new Workshop();
c1.makeClean();
c2.makeClean();
e.makeClean();
}
}
Output :
Clean Facility
Care has been taken
Clean Office
Clean Workshop
Clean Facility
By composition, we can achieve adapter pattern. It is also called wrapper. For
example, a Data class has already been designed and well tested. You want to
adapt such class to your system. You may declare it as a variable and wrapper
or embed it into your class.
//well-tested class
class Data {
public void add(Info){}
public void delete(Info) {}
public void modify(Info){}
//...
}
//Use Data class in your own class
class AdaptData {
Data data;
public void add(Info i) {
data.add(i);
//more job
}
public void delete(Info i) {
data.delete(i);
//more job
}
public void modify(Info i) {
data.modify(i);
//more job
}
//more stuff here
//...
}
Bridge Pattern
Define bridge pattern
 Decouple an abstraction or interface from its implementation so that the two
can vary independently.
 The Bridge Pattern is used to separate out the interface from its
implementation. Doing this gives the flexibility so that both can vary
independently.
 Where to use & benefits
Want to separate abstraction and implementation permanently
Share an implementation among multiple objects
Want to improve extensibility
Hide implementation details from clients
Related patterns include
 Abstract Factory, which can be used to create and configure a
particular bridge.
 Adapter, which makes unrelated classes work together, whereas a
bridge makes a clear-cut between abstraction and implementation.
Example of bridge pattern
 If you have a question database, you may want to
develop a program to display it based on the user
selection. The following is a simple example to show how
to use a Bridge pattern to decouple the relationship
among the objects.
 import java.util.*;
//abstraction
interface Question {
public void nextQuestion();
public void priorQuestion();
public void newQuestion(String q);
public void deleteQuestion(String q);
public void displayQuestion();
public void displayAllQuestions();
}
//implementation
class QuestionManager {
protected Question questDB; //instantiate it later
public String catalog;
public QuestionManager(String catalog) {
this.catalog = catalog;
}
public void next() {
questDB.nextQuestion();
}
public void prior() {
questDB.priorQuestion();
}
public void newOne(String quest) {
questDB.newQuestion(quest);
}
public void delete(String quest) {
questDB.deleteQuestion(quest);
}
public void display() {
questDB.displayQuestion();
}
public void displayAll() {
System.out.println("Question Catalog: " + catalog);
questDB.displayAllQuestions();
}
}
//further implementation
class QuestionFormat extends QuestionManager {
public QuestionFormat(String catalog){
super(catalog);
}
public void displayAll() {
System.out.println("n~~~~~~~~~~~~~~~~~~~~~~~~");
super.displayAll();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
 //decoupled implementation
class JavaQuestions implements Question {
private List questions = new ArrayList();
private int current = 0;
public JavaQuestions() {
//load from a database and fill in the container
questions.add("What is Java? ");
questions.add("What is an interface? ");
questions.add("What is cross-platform? ");
questions.add("What is UFT-8? ");
questions.add("What is abstract? ");
questions.add("What is Thread? ");
questions.add("What is multi-threading? ");
}
public void nextQuestion() {
if( current <= questions.size() - 1 )
current++;
}
public void priorQuestion() {
if( current > 0 )
current--;
}
public void newQuestion(String quest) {
questions.add(quest);
}
public void deleteQuestion(String quest) {
questions.remove(quest);
}
public void displayQuestion() {
System.out.println( questions.get(current) );
}
public void displayAllQuestions() {
for (String quest : questions) {
System.out.println(quest);
}
}
}
class TestBridge {
public static void main(String[] args) {
QuestionFormat questions = new QuestionFormat("Java Language");
questions.questDB = new JavaQuestions();//can be hooked up with other
question class
//questions.questDB = new CsharpQuestions();
//questions.questDB = new CplusplusQuestions();
questions.display();
questions.next();
questions.newOne("What is object? ");
questions.newOne("What is reference type?");
questions.displayAll();
}
}
 //need jdk1.5 to compile
Output :
What is Java?
~~~~~~~~~~~~~~~~~~~~~~~~
Question Catalog: Java Language
What is Java?
What is an interface?
What is cross-platform?
What is UFT-8?
What is abstract?
What is Thread?
What is multi-threading?
What is object?
What is reference type?
~~~~~~~~~~~~~~~~~~~~~~~~
Note that the JavaQuestion class can be launched independently
and work as its own system. Here we just show you how to use
Bridge pattern to decouple the interface from its implementation.
Composite pattern
Define Composite pattern
 Build a complex object out of elemental objects and itself like a tree structure.
 In developing applications, we come across components which are individual
objects and also can be collection of objects. Composite pattern can represent
both the conditions. In this pattern, you can develop tree structures for
representing part-whole hierarchies.
 Where to use & benefits
Want to represent a part-whole relationship like tree folder system
Group components to form larger components, which in turn can be grouped to
form still larger components.
Related patterns include
 Decorator, which is often used with composite pattern and with the same
parent class.
 Flyweight, which is used with composite pattern to share components.
 Iterator, which is used to traverse the composites.
 Visitor, which localizes operations across composite and leaf classes.
Example of composite pattern
 A component has many elements and itself which has many
elements and itself, etc. A file system is a typical example. Directory
is a composite pattern. When you deal with Directory object, if
isFile() returns true, work on file, if isDirectory() returns true, work on
Directory object.
class Directory {
Directory dir;
File[] f;
...
boolean isDirectory() {
return f == null;
}
boolean isFile() {
return f != null;
}
File getFile(int i) {
if (isFile())
return f[i];
return null'
}
Directory getDirectory() {
if (isDirectory())
return dir;
return null;
}
....
}
For example, General Manager may have several employees and some of
employees are Managers which have several employees. To illustrate such issue, we
design a simple Manager class.
class Employee {
String name;
double salary;
Employee(String n, double s){
name = n;
salary = s;
}
String getName() {
return name;
}
double getSalary() {
return salary;
}
public String toString() {
return "Employee " + name;
}
}
class Manager {
Manager mgr;
Employee[] ely;
String dept;
Manager(Manager mgr,Employee[] e, String d ) {
this(e, d);
this.mgr = mgr;
}
Manager(Employee[] e, String d) {
ely = e;
dept =d;
}
String getDept() {
return dept;
}
Manager getManager() {
return mgr;
}
Employee[] getEmployee() {
return ely;
}
public String toString() {
return dept + " manager";
}
}
class Test {
public static void main(String[] args) {
Employee[] e1 = {new Employee("Aaron", 50),
new Employee("Betty", 60)};
Manager m1 = new Manager(e1, "Accounting");
Employee[] e2 = {new Employee("Cathy", 70),
new Employee("Dan", 80),
new Employee("Eliz", 90)};
Manager m2 = new Manager(m1, e2, "Production");
System.out.println(m2);
Employee[] emp = m2.getEmployee();
if (emp != null)
for (int k = 0; k < emp.length; k++)
System.out.println(" "+emp[k]+" Salary: $"+
emp[k].getSalary());
Manager m = m2.getManager();
System.out.println(" " + m);
if (m!= null) {
Employee[] emps = m.getEmployee();
if (emps != null)
for (int k = 0; k < emps.length; k++)
System.out.println(" " + emps[k]+" Salary: $"+
emps[k].getSalary());
}
}
}
Output :
Production manager
Employee Cathy Salary: $70.0
Employee Dan Salary: $80.0
Employee Eliz Salary: $90.0
Accounting manager
Employee Aaron Salary: $50.0
Employee Betty Salary: $60.0
Decorator Pattern
Define decorator pattern
 Attach additional responsibilities or functions to an object dynamically or statically. Also known
as Wrapper.
 The decorator pattern helps to add behavior or responsibilities to an object. This is also called
“Wrapper”. Suppose we have some 6 objects and 2 of them need a special behavior, we can do
this with the help of a decorator.
 Where to use & benefits
Provide an alternative to subclassing.
Add new function to an object without affecting other objects.
Make a responsibility easily added and removed dynamically.
More flexibility than static inheritance.
Transparent to the object.
Related patterns include
 Adapter pattern, which provides a different interface to the object it adapts,
whereas a decorator changes an object's responsibilities,
 Proxy pattern, which controls access to the object, whereas a decorator
focuses on adding new functions to an object,
 Composite pattern, which aggregates an object, whereas a decorator adds
additional responsibilities to an object, and
 Strategy pattern, which changes the guts of an object, whereas a decorator
changes the skin of an object.
 Facade pattern, which provides a way of hiding a complex class, whereas a
decorator adds function by wrapping a class.
Example of decorator pattern
 A JScrollPane object can be used to decorate a JTextArea object or a
JEditorPane object. A window can be decorated with different borders like
BevelBorder, CompoundBorder, EtchedBorder TitledBorder etc. These border
classes working as decorators are provided in Java API.
Decorator pattern can be used in a non-visual fashion. For example,
BufferedInputStream, DataInputStream, and CheckedInputStream are
decorating objects of FilterInputStream class. These decorators are standard
Java API classes.
To illustrate a simple decorator pattern in non-visual manner, we design a
class that prints a number. We create a decorator class that adds a text to
the Number object to indicate that such number is a random number. Of
course we can subclass the Number class to achieve the same goal. But the
decorator pattern provides us an alternative way.
 import java.util.Random;
class Number {
public void print() {
System.out.println(new Random().nextInt());
}
}
class Decorator {
public Decorator() {
System.out.print("Random number: ");//add a description to the number printed
new Number().print();
}
}
class SubNumber extends Number{
public SubNumber() {
super();
System.out.print("Random number: ");
print();
}
}
class Test {
public static void main(String[] args) {
new Decorator();
new SubNumber();
}
}
Output :
Random number: 145265744
Random number: 145265755
Facade Pattern
Define facade pattern
 Make a complex system simpler by providing a unified or general interface, which is a higher layer to
these subsystems.
 Facade as the name suggests means the face of the building. The people walking past the road can
only see this glass face of the building. They do not know anything about it, the wiring, the pipes and
other complexities. The face hides all the complexities of the building and displays a friendly face.
 Where to use & benefits
Want to reduce complexities of a system.
Decouple subsystems , reduce its dependency, and improve portability.
Make an entry point to your subsystems.
Minimize the communication and dependency between subsystems.
Security and performance consideration.
Shield clients from subsystem components.
Simplify generosity to specification.
Related patterns include
 Abstract Factory, which is often used to create an interface for a
subsystem in an independent way, and can be used as an
alternative way to a facade.
 Singleton, which is often used with a facade.
 Mediator, which is similar to facade, but a facade doesn't define
new functionality to the subsystem.
Example of facade pattern
 JDBC design is a good example of Façade pattern. A database design is
complicated. JDBC is used to connect the database and manipulate data
without exposing details to the clients.
Security of a system may be designed with Façade pattern. Clients'
authorization to access information may be classified. General users may be
allowed to access general information; special guests may be allowed to
access more information; administrators and executives may be allowed to
access the most important information. These subsystems may be generalized
by one interface. The identified users may be directed to the related
subsystems.
 interface General {
public void accessGeneral();
}
interface Special extends General {
public void accessSpecial();
}
interface Private extends General {
public void accessPrivate();
}
class GeneralInfo implements General {
public void accessGeneral() {
//...
}
//...
}
class SpecialInfo implements Special{
public void accessSpecial() {
//...
}
public void accessGeneral() {}
//...
}
class PrivateInfo implements Private, Special {
public void accessPrivate() {
// ...
}
public void accessSpecial() {
//...
}
public void accessGeneral() {
// ...
}
//...
}
class Connection {
//...
if (user is unauthorized) throw new Exception();
if (user is general) return new GeneralInfo();
if (user is special) return new SpecialInfo();
if (user is executive) return new PrivateInfo();
//...
}
 The above code example illustrates that the whole system is not
exposed to the clients. It depends on the user classification.
Mr. SudHakar Chavali proposes a better design, similar to the above,
but avoids repeated code. Look at code below.
interface General {
public void accessGeneral();
}
interface Special extends General {
public void accessSpecial();
}
interface Private extends General {
public void accessPrivate();
}
class GeneralInfo implements General {
public void accessGeneral() {
//...
}
//...
}
class SpecialInfo extends GeneralInfo implements Special{
public void accessSpecial() {
//...
}
}
class PrivateInfo extends SpecialInfo implements Private {
public void accessPrivate() {
// ...
}
//...
}
To avoid repeated code, SpecialInfo become subclass of GeneralInfo
and PrivateInfo becomes subclass of SpecialInfo. When a person is
exposed to special information, that person is allowed to access
general information also. When a person is exposed to private
information, that person is allowed to access general information and
special information also.
Flyweight Pattern
Define flyweight pattern
 Make instances of classes on the fly to improve performance efficiently, like individual
characters or icons on the screen.
 The pattern here states about a mechanism by which you can avoid creating a large
number of object instances to represent the entire system.
 Where to use & benefits
Need to instantiate a large amount of small and fine-grained classes.
Need icons to represent object.
An object extrinsic state can be shared by classes.
Reduce the number of objects created, decrease memory footprint and increase
performance.
Increase runtime cost associated with transferring, finding, or computing extrinsic data.
Related patterns include
 Composite, which supports recursive structures, whereas an
flyweight is often applied on it.
 Factory Method, which produces specific object upon requirement,
whereas an flyweight uses it to reduce objects.
 State, which allows an object to alter its behavior when its internal
state is changed, whereas a flyweight is best implemented on it.
 Strategy, which allows an algorithm vary independently to suit its
needs, whereas a flyweight is based on such strategy.
Example of flyweight pattern
 In order to share an object, we may declare an interface and an
intrinsic state through which flyweights can receive and act on it. If
you want to show a file system with folders to show the directories
or subdirectories, you don't need to load all the files or directories at
one loading time. You may show the upper level folders first. If the
user clicks a folder, then load its subdirectories and files. The shared
trigger is mouse-clicked. The composite pattern may be combined
to define the flyweight system.
 class Folder {
void draw(..) {}
}
class FolderFactory {
...
if (selected) {
return aFolder;
else
return aFile;
...
}
...
To show how to use flyweight to reduce object creation, we will make a
program to draw 1000 circles with 6 different colors. Before we customize it
to a flyweight design, it is coded as follows:
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Test extends JFrame{
private static final Color colors[] = { Color.red, Color.blue,
Color.yellow, Color.orange,
Color.black, Color.white };
private static final int WIDTH_ = 400,
HEIGHT = 400,
NUMBER_OF_CIRCLES = 1000;
public Test() {
Container contentPane = getContentPane();
JButton button = new JButton("Draw Circle");
final JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Graphics g = panel.getGraphics();
for(int i=0; i < NUMBER_OF_CIRCLES; ++i) {
g.setColor(getRandomColor());
int r = getRandomR();
g.drawOval(getRandomX(), getRandomY(), r, r);
}
}
});
}
 private int getRandomX() {
return (int)(Math.random()*WIDTH );
}
private int getRandomY() {
return (int)(Math.random()*HEIGHT);
}
private int getRandomR() {
return (int)(Math.random()*(HEIGHT/10));
}
private Color getRandomColor() {
return colors[(int)(Math.random()*colors.length)];
}
public static void main(String[] args) {
Test test = new Test();
}
}
Copy, paste above code, and run it to see the functionality.
Output :
 Note that the above program doesn't take advantage of reusability of OOP.
We will customize it and make a Circle object, so the Circle object can be
reused.
class Circle {
private Color color;
public Circle(Color color) {
this.color = color;
}
public void draw(Graphics g, int x, int y, int r) {
g.setColor(color);
g.drawOval(x, y, r, r);
}
}
Then we rewrite the program. It is possible for people to rewrite with Circle
object in the following way:
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Test extends JFrame{
private static final Color colors[] = { Color.red, Color.blue,
Color.yellow, Color.orange,
Color.black, Color.white };
private static final int WIDTH = 400,
HEIGHT = 400,
NUMBER_OF_CIRCLES = 1000;
public Test() {
Container contentPane = getContentPane();
JButton button = new JButton("Draw Circle");
final JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
setSize(WIDTH ,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Graphics g = panel.getGraphics();
for(int i=0; i < NUMBER_OF_CIRCLES; ++i) {
Circle circle = new Circle(getRandomColor());
circle.draw(g, getRandomX(), getRandomY(), getRandomR());//1000
object created.
}
}
});
}
 private int getRandomX() {
return (int)(Math.random()*WIDTH );
}
private int getRandomY() {
return (int)(Math.random()*HEIGHT);
}
private int getRandomR() {
return (int)(Math.random()*(HEIGHT/10));
}
private Color getRandomColor() {
return colors[(int)(Math.random()*colors.length)];
}
public static void main(String[] args) {
Test test = new Test();
}
}
From the above code, you may note that 1000 circle object has been created.
It is memory consuming.
To improve it, we will create a CircleFactory class to customize it by using
flyweight design pattern. Since we just draw circle with different colors, we
can store color info in a hashmap. If a circle has been drawn, the new circle
will be checked with color. If the circle with the same color has been found in
the hashmap, the circle will share the instance which is picked up from the
hashmap instead of creating a new one. We will reuse the object with
different state, that is to say we will share the instance and draw the circle
with different start position and radius on the fly.
class CircleFactory {
//store color
private static final HashMap circleByColor = new HashMap();
public static Circle getCircle(Color color) {
Circle circle = (Circle)circleByColor.get(color);
if(circle == null) {
circle = new Circle(color);
circleByColor.put(color, circle);
System.out.println("Creating " + color + " circle");//see how many
objects we create on command line
}
return circle;
}
}
So our test program will be coded as follows:
import java.awt.*;
import java.util.HashMap;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
 class Test extends JFrame{
private static final Color colors[] = { Color.red, Color.blue,
Color.yellow, Color.orange,
Color.black, Color.white };
private static final int WIDTH = 400,
HEIGHT = 400,
NUMBER_OF_CIRCLES = 1000;
public Test() {
Container contentPane = getContentPane();
JButton button = new JButton("Draw Circle");
final JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Graphics g = panel.getGraphics();
for(int i=0; i < NUMBER_OF_CIRCLES; ++i) {
Circle circle = CircleFactory.getCircle(getRandomColor());
circle.draw(g, getRandomX(),
getRandomY(),getRandomR());
//Since we have 6 different colors, we have 6 objects
created.
}
}
});
}
public static void main(String[] args) {
Test test = new Test();
}
private int getRandomX() {
return (int)(Math.random()*WIDTH );
}
private int getRandomY() {
return (int)(Math.random()*HEIGHT);
}
private int getRandomR() {
return (int)(Math.random()*(HEIGHT/10));
}
private Color getRandomColor() {
return colors[(int)(Math.random()*colors.length)];
}
}
 class CircleFactory {
private static final HashMap circleByColor = new HashMap();
public static Circle getCircle(Color color) {
Circle circle = (Circle)circleByColor.get(color);
if(circle == null) {
circle = new Circle(color);
circleByColor.put(color, circle);
System.out.println("Creating " + color + " circle");
}
return circle;
}
}
class Circle {
private Color color;
public Circle(Color color) {
this.color = color;
}
public void draw(Graphics g, int x, int y, int r) {
g.setColor(color);
g.drawOval(x, y, r, r);
}
}
Copy, paste above code and run it. You will see the printout from the
command line, that you only have 6 objects created, not 1000 objects
because you only have 6 colors. Such a big reduction of object
creation will improve your program performance dramatically.
Output :
Creating java.awt.Color[r=255,g=0,b=0] circle
Creating java.awt.Color[r=0,g=0,b=0] circle
Creating java.awt.Color[r=255,g=200,b=0] circle
Creating java.awt.Color[r=255,g=255,b=0] circle
Creating java.awt.Color[r=0,g=0,b=255] circle
Creating java.awt.Color[r=255,g=255,b=255] circle
 Flyweight design is effective with instantiating a large amount of small and fine-
grained classes by combining with factory design pattern.
If you have jdk1.5 installed, you may need to use a tool to check if you save the
memory by running your commands as follows:
C:> java -Dcom.sun.management.jmxremote Test
And open another console as follows:
C:> jconsole
The jconsole tool will hook up your program Test to give your statistic numbers
about your program, such as threads, heap, memory, VM, etc.
String class is designed with Flyweight design pattern. It has similar structure as above
example. When you create a string constant, such constant is stored in a pool. When
the second string is created, it will be checked to see if it has been created. If it is true,
the second string instance will be picked up from the string pool instead of creating a
new one. This is why the following code makes sense, but bothers many people.
String s1 = "hello";
String s2 = "hello"; //store in a string pool.
String s3 = new String("hello");
System.out.println(s1==s2); //true, share the same memmory address
System.out.println(s1==s3); //false
Proxy Pattern
Define proxy pattern
 Use a simple object to represent a complex one or provide a placeholder for another object to
control access to it.
 The proxy pattern is used when you need to represent a complex with a simpler one. If creation
of object is expensive, its creation can be postponed till the very need arises and till then, a
simple object can represent it. This simple object is called the “Proxy” for the complex object
 Where to use & benefits
If creating an object is too expensive in time or memory.
Postpone the creation until you need the actual object.
Load a large image (time consuming).
Load a remote object over network during peak periods.
Access right is required to a complex system.
Related patterns include
 Adapter pattern, which provides a different interface to the
object it adapts, whereas a proxy provides the same interface as
its subject, and
 Decorator pattern, which focuses on adding new functions to an
object, whereas a proxy controls access to the object.
Example of proxy pattern
 When loading a large image, you may create some light object to
represent it until the image is loaded completely. Usually a proxy
object has the same methods as the object it represents. Once the
object is loaded, it passes on the actual object. For example,
 abstract class Graphic {
public abstract void load();
public abstract void draw();
...
}
class Image extends Graphic{
public void load() {
...
}
public void draw() {
...
}
...
}
class ImgProxy extends Graphic {
public void load() {
if(image == null) {
image = new Image(filename);
}
...
public void draw() {
...
}
...
}
Structural pattern 3
Structural pattern 3

More Related Content

What's hot

Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
Arsen Gasparyan
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
Michael Heron
 
Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
Danairat Thanabodithammachari
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
11prasoon
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
Eduardo Bergavera
 
CLASSES, STRUCTURE,UNION in C++
CLASSES, STRUCTURE,UNION in C++CLASSES, STRUCTURE,UNION in C++
CLASSES, STRUCTURE,UNION in C++
Prof Ansari
 
Interface
InterfaceInterface
Interface
kamal kotecha
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
Vince Vo
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
Jonathan Simon
 
Modularization Strategies - Fixing Class and Package Tangles
Modularization Strategies - Fixing Class and Package TanglesModularization Strategies - Fixing Class and Package Tangles
Modularization Strategies - Fixing Class and Package Tangles
CodeOps Technologies LLP
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
ilias ahmed
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
Jamie (Taka) Wang
 
Mca 504 dotnet_unit3
Mca 504 dotnet_unit3Mca 504 dotnet_unit3
Creational Design Patterns
Creational Design PatternsCreational Design Patterns
Creational Design Patterns
Jamie (Taka) Wang
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
sandy14234
 
Design patterns illustrated-2015-03
Design patterns illustrated-2015-03Design patterns illustrated-2015-03
Design patterns illustrated-2015-03
Herman Peeren
 
Javascript closures
Javascript closures Javascript closures
Javascript closures
VNG
 

What's hot (20)

Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
 
Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Introduction to php oop
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
CLASSES, STRUCTURE,UNION in C++
CLASSES, STRUCTURE,UNION in C++CLASSES, STRUCTURE,UNION in C++
CLASSES, STRUCTURE,UNION in C++
 
Interface
InterfaceInterface
Interface
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
 
Modularization Strategies - Fixing Class and Package Tangles
Modularization Strategies - Fixing Class and Package TanglesModularization Strategies - Fixing Class and Package Tangles
Modularization Strategies - Fixing Class and Package Tangles
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
Mca 504 dotnet_unit3
Mca 504 dotnet_unit3Mca 504 dotnet_unit3
Mca 504 dotnet_unit3
 
Creational Design Patterns
Creational Design PatternsCreational Design Patterns
Creational Design Patterns
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
Design patterns illustrated-2015-03
Design patterns illustrated-2015-03Design patterns illustrated-2015-03
Design patterns illustrated-2015-03
 
Javascript closures
Javascript closures Javascript closures
Javascript closures
 

Similar to Structural pattern 3

Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
Savio Sebastian
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
ssuser7f90ae
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Rafael Coutinho
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
rani marri
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdf
AdilAijaz3
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdf
Kp Sharma
 
Java mcq
Java mcqJava mcq
Java mcq
avinash9821
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
Design patterns
Design patternsDesign patterns
Design patterns
Anas Alpure
 
Object Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;sObject Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;s
vivek p s
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
G C Reddy Technologies
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Java 06
Java 06Java 06
Java 06
Loida Igama
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
Shawn Brito
 
Java interface
Java interfaceJava interface
Java interface
Arati Gadgil
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
Somenath Mukhopadhyay
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
Arjun Shanka
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
Gaurav Tyagi
 
Ej Chpt#4 Final
Ej Chpt#4 FinalEj Chpt#4 Final
Ej Chpt#4 Final
Chandan Benjaram
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
amitarcade
 

Similar to Structural pattern 3 (20)

Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdf
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdf
 
Java mcq
Java mcqJava mcq
Java mcq
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Object Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;sObject Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;s
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Java 06
Java 06Java 06
Java 06
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Java interface
Java interfaceJava interface
Java interface
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Ej Chpt#4 Final
Ej Chpt#4 FinalEj Chpt#4 Final
Ej Chpt#4 Final
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 

More from Naga Muruga

CHAITANYA UNIVERSITY - BEST POSTER.pdf
CHAITANYA UNIVERSITY - BEST POSTER.pdfCHAITANYA UNIVERSITY - BEST POSTER.pdf
CHAITANYA UNIVERSITY - BEST POSTER.pdf
Naga Muruga
 
AMET - BEST PRESENTATION.pdf
AMET - BEST PRESENTATION.pdfAMET - BEST PRESENTATION.pdf
AMET - BEST PRESENTATION.pdf
Naga Muruga
 
Intro to Git
Intro to GitIntro to Git
Intro to Git
Naga Muruga
 
DEvOpS, CI/CD For Beginners.pdf
DEvOpS, CI/CD For Beginners.pdfDEvOpS, CI/CD For Beginners.pdf
DEvOpS, CI/CD For Beginners.pdf
Naga Muruga
 
API and Web Service Introduction .pdf
API and Web Service Introduction .pdfAPI and Web Service Introduction .pdf
API and Web Service Introduction .pdf
Naga Muruga
 
Naga muruga resume
Naga muruga resumeNaga muruga resume
Naga muruga resume
Naga Muruga
 
Self Healing Materials - A Review
Self Healing Materials - A ReviewSelf Healing Materials - A Review
Self Healing Materials - A Review
Naga Muruga
 
Fundamentals of Manuscript Preparation
Fundamentals of Manuscript PreparationFundamentals of Manuscript Preparation
Fundamentals of Manuscript Preparation
Naga Muruga
 
Auto CAD (Beginner)
Auto CAD (Beginner)Auto CAD (Beginner)
Auto CAD (Beginner)
Naga Muruga
 
Content Writing
Content WritingContent Writing
Content Writing
Naga Muruga
 
Boilers, Types and Energy Efficiency
Boilers, Types and Energy EfficiencyBoilers, Types and Energy Efficiency
Boilers, Types and Energy Efficiency
Naga Muruga
 
Project Management Essentials
Project Management EssentialsProject Management Essentials
Project Management Essentials
Naga Muruga
 
Lean Six Sigma White Belt
Lean Six Sigma White BeltLean Six Sigma White Belt
Lean Six Sigma White Belt
Naga Muruga
 
Basics of Drives and Motors
Basics of Drives and MotorsBasics of Drives and Motors
Basics of Drives and Motors
Naga Muruga
 
Supply Chain
Supply ChainSupply Chain
Supply Chain
Naga Muruga
 
Green walls
Green wallsGreen walls
Green walls
Naga Muruga
 
Anti juice jacking smart solar charger
Anti juice jacking smart solar chargerAnti juice jacking smart solar charger
Anti juice jacking smart solar charger
Naga Muruga
 
Top 32 technologies
Top 32 technologiesTop 32 technologies
Top 32 technologies
Naga Muruga
 
Controversy on feminism
Controversy on feminismControversy on feminism
Controversy on feminism
Naga Muruga
 
Unicef poster
Unicef posterUnicef poster
Unicef poster
Naga Muruga
 

More from Naga Muruga (20)

CHAITANYA UNIVERSITY - BEST POSTER.pdf
CHAITANYA UNIVERSITY - BEST POSTER.pdfCHAITANYA UNIVERSITY - BEST POSTER.pdf
CHAITANYA UNIVERSITY - BEST POSTER.pdf
 
AMET - BEST PRESENTATION.pdf
AMET - BEST PRESENTATION.pdfAMET - BEST PRESENTATION.pdf
AMET - BEST PRESENTATION.pdf
 
Intro to Git
Intro to GitIntro to Git
Intro to Git
 
DEvOpS, CI/CD For Beginners.pdf
DEvOpS, CI/CD For Beginners.pdfDEvOpS, CI/CD For Beginners.pdf
DEvOpS, CI/CD For Beginners.pdf
 
API and Web Service Introduction .pdf
API and Web Service Introduction .pdfAPI and Web Service Introduction .pdf
API and Web Service Introduction .pdf
 
Naga muruga resume
Naga muruga resumeNaga muruga resume
Naga muruga resume
 
Self Healing Materials - A Review
Self Healing Materials - A ReviewSelf Healing Materials - A Review
Self Healing Materials - A Review
 
Fundamentals of Manuscript Preparation
Fundamentals of Manuscript PreparationFundamentals of Manuscript Preparation
Fundamentals of Manuscript Preparation
 
Auto CAD (Beginner)
Auto CAD (Beginner)Auto CAD (Beginner)
Auto CAD (Beginner)
 
Content Writing
Content WritingContent Writing
Content Writing
 
Boilers, Types and Energy Efficiency
Boilers, Types and Energy EfficiencyBoilers, Types and Energy Efficiency
Boilers, Types and Energy Efficiency
 
Project Management Essentials
Project Management EssentialsProject Management Essentials
Project Management Essentials
 
Lean Six Sigma White Belt
Lean Six Sigma White BeltLean Six Sigma White Belt
Lean Six Sigma White Belt
 
Basics of Drives and Motors
Basics of Drives and MotorsBasics of Drives and Motors
Basics of Drives and Motors
 
Supply Chain
Supply ChainSupply Chain
Supply Chain
 
Green walls
Green wallsGreen walls
Green walls
 
Anti juice jacking smart solar charger
Anti juice jacking smart solar chargerAnti juice jacking smart solar charger
Anti juice jacking smart solar charger
 
Top 32 technologies
Top 32 technologiesTop 32 technologies
Top 32 technologies
 
Controversy on feminism
Controversy on feminismControversy on feminism
Controversy on feminism
 
Unicef poster
Unicef posterUnicef poster
Unicef poster
 

Recently uploaded

一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
skuxot
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
yokeleetan1
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
zwunae
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
Divyam548318
 
introduction to solar energy for engineering.pdf
introduction to solar energy for engineering.pdfintroduction to solar energy for engineering.pdf
introduction to solar energy for engineering.pdf
ravindarpurohit26
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
This is my Environmental physics presentation
This is my Environmental physics presentationThis is my Environmental physics presentation
This is my Environmental physics presentation
ZainabHashmi17
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
NidhalKahouli2
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 

Recently uploaded (20)

一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
 
introduction to solar energy for engineering.pdf
introduction to solar energy for engineering.pdfintroduction to solar energy for engineering.pdf
introduction to solar energy for engineering.pdf
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
This is my Environmental physics presentation
This is my Environmental physics presentationThis is my Environmental physics presentation
This is my Environmental physics presentation
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 

Structural pattern 3

  • 1. Structural Pattern - 3 By, D. B. Naga Muruga, Dept of Mechanical Engineering, Sriram Engineering College
  • 2. Adapter Pattern Define Adapter pattern  Convert the existing interfaces to a new interface to achieve compatibility and reusability of the unrelated classes in one application. Also known as Wrapper pattern.  The Adapter pattern is used so that two unrelated interfaces can work together. The joining between them is called an Adapter. This is something like we convert interface of one class into interface expected by the client. We do that using an Adapter.  Where to use & benefits Try to match an interface(WindowAdapter, etc.) Make unrelated classes work together. Multiple compatibility. Increase transparency of classes. Make a pluggable kit. Delegate objects. Highly class reusable. Achieve the goal by inheritance or by composition Related patterns include Proxy, which provides the same interface as its subject, whereas an adapter provides a different interface to the object it adapts. Decorator, which focuses on adding new functions to an object, whereas an adapter coordinates two different objects. Bridge, which tries to separate an interface from its implementation and make an object vary independently, whereas an adapter tries to change and cooperate the interface of an object.
  • 3. Example of Adapter pattern  The famous adapter classes in Java API are WindowAdapter,ComponentAdapter, ContainerAdapter, FocusAdapter, KeyAdapter, MouseAdapter and MouseMotionAdapter. As you know, WindowListner interface has seven methods. Whenever your class implements such interface, you have to implements all of the seven methods. WindowAdapter class implements WindowListener interface and make seven empty implementation. When you class subclass WindowAdapter class, you may choose the method you want without restrictions. The following give such an example.
  • 4.  public interface Windowlistener { public void windowClosed(WindowEvent e); public void windowOpened(WindowEvent e); public void windowIconified(WindowEvent e); public void windowDeiconified(WindowEvent e); public void windowActivated(WindowEvent e); public void windowDeactivated(WindowEvent e); public void windowClosing(WindowEvent e); } public class WindowAdapter implements WindowListner{ public void windowClosed(WindowEvent e){} public void windowOpened(WindowEvent e){} public void windowIconified(WindowEvent e){} public void windowDeiconified(WindowEvent e){} public void windowActivated(WindowEvent e){} public void windowDeactivated(WindowEvent e){} public void windowClosing(WindowEvent e){} } Here is a test program import javax.swing.*; import java.awt.event.*; class Test extends JFrame { public Test () { setSize(200,200); setVisible(true); addWindowListener(new Closer()); } public static void main(String[] args) { new Test(); } class Closer extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } } To reuse classes and make new class compatible with existing ones. For example, A clean system is already designed, you want to add more job in, the Extra interface uses adapter pattern to plug in the existing system. interface Clean { public void makeClean(); } class Office implements Clean{ public void makeClean() { System.out.println("Clean Office"); } } class Workshop implements Clean{ public void makeClean() { System.out.println("Clean Workshop"); } } interface Extra extends Clean{ public void takeCare(); } class Facility implements Extra{ public void makeClean() { System.out.println("Clean Facility"); }  public void takeCare() { System.out.println("Care has been taken"); } }  In order to reuse Workshop and Office classes, we create an adapter interface Extra and add new job takeCare in the system. class Test { static void Jobs (Extra job) { if (job instanceof Clean) ((Clean)job).makeClean(); if ((Extra)job instanceof Extra) ((Extra)job).takeCare(); } public static void main(String[] args) { Extra e = new Facility(); Jobs(e); Clean c1 = new Office(); Clean c2 = new Workshop(); c1.makeClean(); c2.makeClean(); e.makeClean(); } } Output : Clean Facility Care has been taken Clean Office Clean Workshop Clean Facility By composition, we can achieve adapter pattern. It is also called wrapper. For example, a Data class has already been designed and well tested. You want to adapt such class to your system. You may declare it as a variable and wrapper or embed it into your class. //well-tested class class Data { public void add(Info){} public void delete(Info) {} public void modify(Info){} //... } //Use Data class in your own class class AdaptData { Data data; public void add(Info i) { data.add(i); //more job } public void delete(Info i) { data.delete(i); //more job } public void modify(Info i) { data.modify(i); //more job } //more stuff here //... }
  • 5. Bridge Pattern Define bridge pattern  Decouple an abstraction or interface from its implementation so that the two can vary independently.  The Bridge Pattern is used to separate out the interface from its implementation. Doing this gives the flexibility so that both can vary independently.  Where to use & benefits Want to separate abstraction and implementation permanently Share an implementation among multiple objects Want to improve extensibility Hide implementation details from clients
  • 6. Related patterns include  Abstract Factory, which can be used to create and configure a particular bridge.  Adapter, which makes unrelated classes work together, whereas a bridge makes a clear-cut between abstraction and implementation.
  • 7. Example of bridge pattern  If you have a question database, you may want to develop a program to display it based on the user selection. The following is a simple example to show how to use a Bridge pattern to decouple the relationship among the objects.
  • 8.  import java.util.*; //abstraction interface Question { public void nextQuestion(); public void priorQuestion(); public void newQuestion(String q); public void deleteQuestion(String q); public void displayQuestion(); public void displayAllQuestions(); } //implementation class QuestionManager { protected Question questDB; //instantiate it later public String catalog; public QuestionManager(String catalog) { this.catalog = catalog; } public void next() { questDB.nextQuestion(); } public void prior() { questDB.priorQuestion(); } public void newOne(String quest) { questDB.newQuestion(quest); } public void delete(String quest) { questDB.deleteQuestion(quest); } public void display() { questDB.displayQuestion(); } public void displayAll() { System.out.println("Question Catalog: " + catalog); questDB.displayAllQuestions(); } } //further implementation class QuestionFormat extends QuestionManager { public QuestionFormat(String catalog){ super(catalog); } public void displayAll() { System.out.println("n~~~~~~~~~~~~~~~~~~~~~~~~"); super.displayAll(); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~"); } }  //decoupled implementation class JavaQuestions implements Question { private List questions = new ArrayList(); private int current = 0; public JavaQuestions() { //load from a database and fill in the container questions.add("What is Java? "); questions.add("What is an interface? "); questions.add("What is cross-platform? "); questions.add("What is UFT-8? "); questions.add("What is abstract? "); questions.add("What is Thread? "); questions.add("What is multi-threading? "); } public void nextQuestion() { if( current <= questions.size() - 1 ) current++; } public void priorQuestion() { if( current > 0 ) current--; } public void newQuestion(String quest) { questions.add(quest); } public void deleteQuestion(String quest) { questions.remove(quest); } public void displayQuestion() { System.out.println( questions.get(current) ); } public void displayAllQuestions() { for (String quest : questions) { System.out.println(quest); } } } class TestBridge { public static void main(String[] args) { QuestionFormat questions = new QuestionFormat("Java Language"); questions.questDB = new JavaQuestions();//can be hooked up with other question class //questions.questDB = new CsharpQuestions(); //questions.questDB = new CplusplusQuestions(); questions.display(); questions.next(); questions.newOne("What is object? "); questions.newOne("What is reference type?"); questions.displayAll(); } }
  • 9.  //need jdk1.5 to compile Output : What is Java? ~~~~~~~~~~~~~~~~~~~~~~~~ Question Catalog: Java Language What is Java? What is an interface? What is cross-platform? What is UFT-8? What is abstract? What is Thread? What is multi-threading? What is object? What is reference type? ~~~~~~~~~~~~~~~~~~~~~~~~ Note that the JavaQuestion class can be launched independently and work as its own system. Here we just show you how to use Bridge pattern to decouple the interface from its implementation.
  • 10. Composite pattern Define Composite pattern  Build a complex object out of elemental objects and itself like a tree structure.  In developing applications, we come across components which are individual objects and also can be collection of objects. Composite pattern can represent both the conditions. In this pattern, you can develop tree structures for representing part-whole hierarchies.  Where to use & benefits Want to represent a part-whole relationship like tree folder system Group components to form larger components, which in turn can be grouped to form still larger components.
  • 11. Related patterns include  Decorator, which is often used with composite pattern and with the same parent class.  Flyweight, which is used with composite pattern to share components.  Iterator, which is used to traverse the composites.  Visitor, which localizes operations across composite and leaf classes.
  • 12. Example of composite pattern  A component has many elements and itself which has many elements and itself, etc. A file system is a typical example. Directory is a composite pattern. When you deal with Directory object, if isFile() returns true, work on file, if isDirectory() returns true, work on Directory object.
  • 13. class Directory { Directory dir; File[] f; ... boolean isDirectory() { return f == null; } boolean isFile() { return f != null; } File getFile(int i) { if (isFile()) return f[i]; return null' } Directory getDirectory() { if (isDirectory()) return dir; return null; } .... } For example, General Manager may have several employees and some of employees are Managers which have several employees. To illustrate such issue, we design a simple Manager class. class Employee { String name; double salary; Employee(String n, double s){ name = n; salary = s; } String getName() { return name; } double getSalary() { return salary; } public String toString() { return "Employee " + name; } } class Manager { Manager mgr; Employee[] ely; String dept; Manager(Manager mgr,Employee[] e, String d ) { this(e, d); this.mgr = mgr; } Manager(Employee[] e, String d) { ely = e; dept =d; } String getDept() { return dept; } Manager getManager() { return mgr; } Employee[] getEmployee() { return ely; } public String toString() { return dept + " manager"; } } class Test { public static void main(String[] args) { Employee[] e1 = {new Employee("Aaron", 50), new Employee("Betty", 60)}; Manager m1 = new Manager(e1, "Accounting"); Employee[] e2 = {new Employee("Cathy", 70), new Employee("Dan", 80), new Employee("Eliz", 90)}; Manager m2 = new Manager(m1, e2, "Production"); System.out.println(m2); Employee[] emp = m2.getEmployee(); if (emp != null) for (int k = 0; k < emp.length; k++) System.out.println(" "+emp[k]+" Salary: $"+ emp[k].getSalary()); Manager m = m2.getManager(); System.out.println(" " + m); if (m!= null) { Employee[] emps = m.getEmployee(); if (emps != null) for (int k = 0; k < emps.length; k++) System.out.println(" " + emps[k]+" Salary: $"+ emps[k].getSalary()); } } } Output : Production manager Employee Cathy Salary: $70.0 Employee Dan Salary: $80.0 Employee Eliz Salary: $90.0 Accounting manager Employee Aaron Salary: $50.0 Employee Betty Salary: $60.0
  • 14. Decorator Pattern Define decorator pattern  Attach additional responsibilities or functions to an object dynamically or statically. Also known as Wrapper.  The decorator pattern helps to add behavior or responsibilities to an object. This is also called “Wrapper”. Suppose we have some 6 objects and 2 of them need a special behavior, we can do this with the help of a decorator.  Where to use & benefits Provide an alternative to subclassing. Add new function to an object without affecting other objects. Make a responsibility easily added and removed dynamically. More flexibility than static inheritance. Transparent to the object.
  • 15. Related patterns include  Adapter pattern, which provides a different interface to the object it adapts, whereas a decorator changes an object's responsibilities,  Proxy pattern, which controls access to the object, whereas a decorator focuses on adding new functions to an object,  Composite pattern, which aggregates an object, whereas a decorator adds additional responsibilities to an object, and  Strategy pattern, which changes the guts of an object, whereas a decorator changes the skin of an object.  Facade pattern, which provides a way of hiding a complex class, whereas a decorator adds function by wrapping a class.
  • 16. Example of decorator pattern  A JScrollPane object can be used to decorate a JTextArea object or a JEditorPane object. A window can be decorated with different borders like BevelBorder, CompoundBorder, EtchedBorder TitledBorder etc. These border classes working as decorators are provided in Java API. Decorator pattern can be used in a non-visual fashion. For example, BufferedInputStream, DataInputStream, and CheckedInputStream are decorating objects of FilterInputStream class. These decorators are standard Java API classes. To illustrate a simple decorator pattern in non-visual manner, we design a class that prints a number. We create a decorator class that adds a text to the Number object to indicate that such number is a random number. Of course we can subclass the Number class to achieve the same goal. But the decorator pattern provides us an alternative way.
  • 17.  import java.util.Random; class Number { public void print() { System.out.println(new Random().nextInt()); } } class Decorator { public Decorator() { System.out.print("Random number: ");//add a description to the number printed new Number().print(); } } class SubNumber extends Number{ public SubNumber() { super(); System.out.print("Random number: "); print(); } } class Test { public static void main(String[] args) { new Decorator(); new SubNumber(); } } Output : Random number: 145265744 Random number: 145265755
  • 18. Facade Pattern Define facade pattern  Make a complex system simpler by providing a unified or general interface, which is a higher layer to these subsystems.  Facade as the name suggests means the face of the building. The people walking past the road can only see this glass face of the building. They do not know anything about it, the wiring, the pipes and other complexities. The face hides all the complexities of the building and displays a friendly face.  Where to use & benefits Want to reduce complexities of a system. Decouple subsystems , reduce its dependency, and improve portability. Make an entry point to your subsystems. Minimize the communication and dependency between subsystems. Security and performance consideration. Shield clients from subsystem components. Simplify generosity to specification.
  • 19. Related patterns include  Abstract Factory, which is often used to create an interface for a subsystem in an independent way, and can be used as an alternative way to a facade.  Singleton, which is often used with a facade.  Mediator, which is similar to facade, but a facade doesn't define new functionality to the subsystem.
  • 20. Example of facade pattern  JDBC design is a good example of Façade pattern. A database design is complicated. JDBC is used to connect the database and manipulate data without exposing details to the clients. Security of a system may be designed with Façade pattern. Clients' authorization to access information may be classified. General users may be allowed to access general information; special guests may be allowed to access more information; administrators and executives may be allowed to access the most important information. These subsystems may be generalized by one interface. The identified users may be directed to the related subsystems.
  • 21.  interface General { public void accessGeneral(); } interface Special extends General { public void accessSpecial(); } interface Private extends General { public void accessPrivate(); } class GeneralInfo implements General { public void accessGeneral() { //... } //... } class SpecialInfo implements Special{ public void accessSpecial() { //... } public void accessGeneral() {} //... } class PrivateInfo implements Private, Special { public void accessPrivate() { // ... } public void accessSpecial() { //... } public void accessGeneral() { // ... } //... } class Connection { //... if (user is unauthorized) throw new Exception(); if (user is general) return new GeneralInfo(); if (user is special) return new SpecialInfo(); if (user is executive) return new PrivateInfo(); //... }  The above code example illustrates that the whole system is not exposed to the clients. It depends on the user classification. Mr. SudHakar Chavali proposes a better design, similar to the above, but avoids repeated code. Look at code below. interface General { public void accessGeneral(); } interface Special extends General { public void accessSpecial(); } interface Private extends General { public void accessPrivate(); } class GeneralInfo implements General { public void accessGeneral() { //... } //... } class SpecialInfo extends GeneralInfo implements Special{ public void accessSpecial() { //... } } class PrivateInfo extends SpecialInfo implements Private { public void accessPrivate() { // ... } //... } To avoid repeated code, SpecialInfo become subclass of GeneralInfo and PrivateInfo becomes subclass of SpecialInfo. When a person is exposed to special information, that person is allowed to access general information also. When a person is exposed to private information, that person is allowed to access general information and special information also.
  • 22. Flyweight Pattern Define flyweight pattern  Make instances of classes on the fly to improve performance efficiently, like individual characters or icons on the screen.  The pattern here states about a mechanism by which you can avoid creating a large number of object instances to represent the entire system.  Where to use & benefits Need to instantiate a large amount of small and fine-grained classes. Need icons to represent object. An object extrinsic state can be shared by classes. Reduce the number of objects created, decrease memory footprint and increase performance. Increase runtime cost associated with transferring, finding, or computing extrinsic data.
  • 23. Related patterns include  Composite, which supports recursive structures, whereas an flyweight is often applied on it.  Factory Method, which produces specific object upon requirement, whereas an flyweight uses it to reduce objects.  State, which allows an object to alter its behavior when its internal state is changed, whereas a flyweight is best implemented on it.  Strategy, which allows an algorithm vary independently to suit its needs, whereas a flyweight is based on such strategy.
  • 24. Example of flyweight pattern  In order to share an object, we may declare an interface and an intrinsic state through which flyweights can receive and act on it. If you want to show a file system with folders to show the directories or subdirectories, you don't need to load all the files or directories at one loading time. You may show the upper level folders first. If the user clicks a folder, then load its subdirectories and files. The shared trigger is mouse-clicked. The composite pattern may be combined to define the flyweight system.
  • 25.  class Folder { void draw(..) {} } class FolderFactory { ... if (selected) { return aFolder; else return aFile; ... } ... To show how to use flyweight to reduce object creation, we will make a program to draw 1000 circles with 6 different colors. Before we customize it to a flyweight design, it is coded as follows: import java.awt.*; import java.awt.Color; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class Test extends JFrame{ private static final Color colors[] = { Color.red, Color.blue, Color.yellow, Color.orange, Color.black, Color.white }; private static final int WIDTH_ = 400, HEIGHT = 400, NUMBER_OF_CIRCLES = 1000; public Test() { Container contentPane = getContentPane(); JButton button = new JButton("Draw Circle"); final JPanel panel = new JPanel(); contentPane.add(panel, BorderLayout.CENTER); contentPane.add(button, BorderLayout.SOUTH); setSize(WIDTH,HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Graphics g = panel.getGraphics(); for(int i=0; i < NUMBER_OF_CIRCLES; ++i) { g.setColor(getRandomColor()); int r = getRandomR(); g.drawOval(getRandomX(), getRandomY(), r, r); } } }); }  private int getRandomX() { return (int)(Math.random()*WIDTH ); } private int getRandomY() { return (int)(Math.random()*HEIGHT); } private int getRandomR() { return (int)(Math.random()*(HEIGHT/10)); } private Color getRandomColor() { return colors[(int)(Math.random()*colors.length)]; } public static void main(String[] args) { Test test = new Test(); } } Copy, paste above code, and run it to see the functionality. Output :
  • 26.
  • 27.  Note that the above program doesn't take advantage of reusability of OOP. We will customize it and make a Circle object, so the Circle object can be reused. class Circle { private Color color; public Circle(Color color) { this.color = color; } public void draw(Graphics g, int x, int y, int r) { g.setColor(color); g.drawOval(x, y, r, r); } } Then we rewrite the program. It is possible for people to rewrite with Circle object in the following way: import java.awt.*; import java.awt.Color; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class Test extends JFrame{ private static final Color colors[] = { Color.red, Color.blue, Color.yellow, Color.orange, Color.black, Color.white }; private static final int WIDTH = 400, HEIGHT = 400, NUMBER_OF_CIRCLES = 1000; public Test() { Container contentPane = getContentPane(); JButton button = new JButton("Draw Circle"); final JPanel panel = new JPanel(); contentPane.add(panel, BorderLayout.CENTER); contentPane.add(button, BorderLayout.SOUTH); setSize(WIDTH ,HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Graphics g = panel.getGraphics(); for(int i=0; i < NUMBER_OF_CIRCLES; ++i) { Circle circle = new Circle(getRandomColor()); circle.draw(g, getRandomX(), getRandomY(), getRandomR());//1000 object created. } } }); }  private int getRandomX() { return (int)(Math.random()*WIDTH ); } private int getRandomY() { return (int)(Math.random()*HEIGHT); } private int getRandomR() { return (int)(Math.random()*(HEIGHT/10)); } private Color getRandomColor() { return colors[(int)(Math.random()*colors.length)]; } public static void main(String[] args) { Test test = new Test(); } } From the above code, you may note that 1000 circle object has been created. It is memory consuming. To improve it, we will create a CircleFactory class to customize it by using flyweight design pattern. Since we just draw circle with different colors, we can store color info in a hashmap. If a circle has been drawn, the new circle will be checked with color. If the circle with the same color has been found in the hashmap, the circle will share the instance which is picked up from the hashmap instead of creating a new one. We will reuse the object with different state, that is to say we will share the instance and draw the circle with different start position and radius on the fly. class CircleFactory { //store color private static final HashMap circleByColor = new HashMap(); public static Circle getCircle(Color color) { Circle circle = (Circle)circleByColor.get(color); if(circle == null) { circle = new Circle(color); circleByColor.put(color, circle); System.out.println("Creating " + color + " circle");//see how many objects we create on command line } return circle; } } So our test program will be coded as follows: import java.awt.*; import java.util.HashMap; import java.awt.Color; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*;
  • 28.  class Test extends JFrame{ private static final Color colors[] = { Color.red, Color.blue, Color.yellow, Color.orange, Color.black, Color.white }; private static final int WIDTH = 400, HEIGHT = 400, NUMBER_OF_CIRCLES = 1000; public Test() { Container contentPane = getContentPane(); JButton button = new JButton("Draw Circle"); final JPanel panel = new JPanel(); contentPane.add(panel, BorderLayout.CENTER); contentPane.add(button, BorderLayout.SOUTH); setSize(WIDTH,HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Graphics g = panel.getGraphics(); for(int i=0; i < NUMBER_OF_CIRCLES; ++i) { Circle circle = CircleFactory.getCircle(getRandomColor()); circle.draw(g, getRandomX(), getRandomY(),getRandomR()); //Since we have 6 different colors, we have 6 objects created. } } }); } public static void main(String[] args) { Test test = new Test(); } private int getRandomX() { return (int)(Math.random()*WIDTH ); } private int getRandomY() { return (int)(Math.random()*HEIGHT); } private int getRandomR() { return (int)(Math.random()*(HEIGHT/10)); } private Color getRandomColor() { return colors[(int)(Math.random()*colors.length)]; } }  class CircleFactory { private static final HashMap circleByColor = new HashMap(); public static Circle getCircle(Color color) { Circle circle = (Circle)circleByColor.get(color); if(circle == null) { circle = new Circle(color); circleByColor.put(color, circle); System.out.println("Creating " + color + " circle"); } return circle; } } class Circle { private Color color; public Circle(Color color) { this.color = color; } public void draw(Graphics g, int x, int y, int r) { g.setColor(color); g.drawOval(x, y, r, r); } } Copy, paste above code and run it. You will see the printout from the command line, that you only have 6 objects created, not 1000 objects because you only have 6 colors. Such a big reduction of object creation will improve your program performance dramatically. Output : Creating java.awt.Color[r=255,g=0,b=0] circle Creating java.awt.Color[r=0,g=0,b=0] circle Creating java.awt.Color[r=255,g=200,b=0] circle Creating java.awt.Color[r=255,g=255,b=0] circle Creating java.awt.Color[r=0,g=0,b=255] circle Creating java.awt.Color[r=255,g=255,b=255] circle
  • 29.
  • 30.  Flyweight design is effective with instantiating a large amount of small and fine- grained classes by combining with factory design pattern. If you have jdk1.5 installed, you may need to use a tool to check if you save the memory by running your commands as follows: C:> java -Dcom.sun.management.jmxremote Test And open another console as follows: C:> jconsole The jconsole tool will hook up your program Test to give your statistic numbers about your program, such as threads, heap, memory, VM, etc. String class is designed with Flyweight design pattern. It has similar structure as above example. When you create a string constant, such constant is stored in a pool. When the second string is created, it will be checked to see if it has been created. If it is true, the second string instance will be picked up from the string pool instead of creating a new one. This is why the following code makes sense, but bothers many people. String s1 = "hello"; String s2 = "hello"; //store in a string pool. String s3 = new String("hello"); System.out.println(s1==s2); //true, share the same memmory address System.out.println(s1==s3); //false
  • 31. Proxy Pattern Define proxy pattern  Use a simple object to represent a complex one or provide a placeholder for another object to control access to it.  The proxy pattern is used when you need to represent a complex with a simpler one. If creation of object is expensive, its creation can be postponed till the very need arises and till then, a simple object can represent it. This simple object is called the “Proxy” for the complex object  Where to use & benefits If creating an object is too expensive in time or memory. Postpone the creation until you need the actual object. Load a large image (time consuming). Load a remote object over network during peak periods. Access right is required to a complex system.
  • 32. Related patterns include  Adapter pattern, which provides a different interface to the object it adapts, whereas a proxy provides the same interface as its subject, and  Decorator pattern, which focuses on adding new functions to an object, whereas a proxy controls access to the object.
  • 33. Example of proxy pattern  When loading a large image, you may create some light object to represent it until the image is loaded completely. Usually a proxy object has the same methods as the object it represents. Once the object is loaded, it passes on the actual object. For example,
  • 34.  abstract class Graphic { public abstract void load(); public abstract void draw(); ... } class Image extends Graphic{ public void load() { ... } public void draw() { ... } ... } class ImgProxy extends Graphic { public void load() { if(image == null) { image = new Image(filename); } ... public void draw() { ... } ... }