0% found this document useful (0 votes)
109 views

CS711 - Design Pattern's

The document discusses different design patterns including the Factory design pattern which defines an interface for creating objects but lets subclasses decide which class to instantiate, and the Singleton pattern which ensures a class has only one instance and provides a global point of access to it. Examples are provided for name parsing using the Factory pattern and for a pizza shop application using different pizza types with the Factory pattern.

Uploaded by

Sahar Raza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views

CS711 - Design Pattern's

The document discusses different design patterns including the Factory design pattern which defines an interface for creating objects but lets subclasses decide which class to instantiate, and the Singleton pattern which ensures a class has only one instance and provides a global point of access to it. Examples are provided for name parsing using the Factory pattern and for a pizza shop application using different pizza types with the Factory pattern.

Uploaded by

Sahar Raza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

CS711 – Software Design 1

Software Design Pattern


• Creational Design Pattern
✓ Factory Design Pattern ----------------------------------------------------------------- 03
✓ Singleton Design Pattern -------------------------------------------------------------- 09
✓ Prototype Design Pattern ------------------------------------------------------------- 11
✓ Builder Design Pattern ----------------------------------------------------------------- 16

• Structural Design Pattern


✓ Adapter or Wrapper Design Pattern ----------------------------------------------- 20
✓ Façade Design Pattern ----------------------------------------------------------------- 21
✓ Composite Design Pattern ------------------------------------------------------------ 23
✓ Flyweight Design Pattern -------------------------------------------------------------- 26
✓ Proxy or Surrogate Design Pattern -------------------------------------------------- 29

• Behavioral Design Pattern


✓ Iterator Design Pattern ----------------------------------------------------------------- 32
✓ Observer or Publish and Subscribe Design Pattern ------------------------------ 34
✓ Templet or Pattern Design Pattern -------------------------------------------------- 37
✓ Memento or Souvenir Design Pattern ---------------------------------------------- 40
✓ Command or Encapsulating Invocation Design Pattern ------------------------ 42

Presented By:

Sheraz Pervaiz
Stuttgart University of Applied Sciences,
Germany

Published By:
www.vumultan.com

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 2

This page is intentionally left Blank

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 3

Creational Design Pattern


Factory Design Pattern
Intent
To define an interface for creating an object but let subclass decides which class to instantiate
as per request of the client.

“Factory Pattern defines an interface for creating the object but let the subclass decide which
class to instantiate. Factory pattern let the class defer instantiation to the sub class”

We want the user to enter the name in either “first name last name or last name, first name”
format. We have made the assumption that there will always be a comma between last name
and first name and space between first name last names. The client does not need to be worried
about which class is to access when it is entering the name in either of the format. Independent
of the format of the data to be entered, system will display first name and last name.

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 4

class Namer {
protected String last; //store last name here
protected String first; //store first name here
public String getFirst(){
return first; //return first name
}
public String getLast() {
return last; //return last name
}
}

class Firstfirst extends Namer { //split first last


public FirstFirst(String s){
int i = s.lastIndexOf(" "); //find sep space
if (i > 0){
first = s.substring(0, i).trim(); //left is first name
last =s.substring(i+1).trim(); //right is last name
} else {
first = “”; // put all in last name
last = s; // if no space
}
}
}

class LastFirst extends Namer { //split last, first


public LastFirst(String s){
int i = s.indexOf(","); //find comma
if (i > 0){
last = s.substring(0, i).trim(); //left is last name
first = s.substring(i + 1).trim(); //right is first name
} else {
last = s; // put all in last name
first = ""; // if no comma
}
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 5

class NameFactory { //returns an instance of LastFirst or FirstFirst


// depending on whether a comma is found
public Namer getNamer(String entry) {
int i = entry.indexOf(","); //comma determines name order
if (i>0)
return new LastFirst(entry); //return one class
else
return new FirstFirst(entry); //or the other
}
}

public class testFactory {


public static void main(String args[]){
NameFactory nfactory = new NameFactory();
String name=“Ali khan”;
Namer namer = nfactory.getNamer(name); // Delegation
//compute the first and last names using the returned class
System.out.println(namer.getFirst());
System.out.println(namer.getLast());
}
}

Pizza Factory Example

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 6

Problem Statement:
There is a pizza shop which is offering different delicious pizza's to it' customer. There are some
standard processes which are involved in a pizza creation like first the pizza is prepared by putting
together all the ingredients, then it is prepared for backing, after baking it is cut and put into the
boxes of as per order placed by the customer. There is different type of pizzas like chees, chicken,
vegetable etc; and this list keeps on increasing with addition of in demand pizza and removal of
not in demand pizzas.

Package PizzaFactory;
Public abstract class Pizza {
String name;
String dough;
String sauce;
Void prepare() {
System.out.println(“Preparing:” +name);
System.out.println(“Dough:” +dough);
System.out.println(“Sauce Used:” +sauce);
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 7

Public abstract class PizzaStore {


Public Pizza orderpizza(string type) {
Pizza pizza;
pizza = null;
pizza = createpizza(type);
}
}

Public class LahorePizzaStore extends PizzaStore {


Pizza createpizza(String type) {
If(type.equals(“Chiken”)) {
returen new LahoreChikenPizza();
}
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
return pizza;
}
abstract pizza createpizza(String type);
}

public class karachiPizzaStore extends PizzaStore {


pizza createPizza(string type) {
if (type.equals(“Thick Crust”)) {
returen new KarachiChikenPizza();
}
return null;
}

Public class LahoreChikenPizza extends Pizza {


Public LahoreChikenPizza() {
name = “Lahore Chiken Pizza”;
sauce = “Nill”;
dough = “thin crust”;
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 8

Public class KarachiChikenPizza extends Pizza {


Public KarachiChikenPizza() {
name = “Karachi Chiken Pizza”;
sauce = “Nill”;
dough = “thin crust”;
}
}

Public class TestingPizzaFactory {


Public static void main (string args[]) {
PizzaStore LahoreBranch = new LahorePizzaStore();
PizzaStore KarachiBranch = new KarachiPizzaStore();
Pizza LahorePizza = LahoreBranch.createPizza(“Chiken”);
System.out.println(“Lahore Pizza:” + lahorePizza.getname());
Pizza KarachiPizza – KarachiBranch.createPizza(“Thick Crust”);
System.out.println(“Karachi Pizza:” + KarachiPizza.getname());
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 9

Singleton Design Pattern


Intent:
Ensure a class has one instance, and provide a global point of access to it.

“Singleton Design Pattern ensures that there is only one instance of a class and provides global
point of access to it”

Static variable + static method

Using Global Variables


Having an instance of the class in a global variable seems like an easy way to maintain the single
instance. All client objects can access this instance in a consistent manner through this global
variable.

public class Singleton {


private volatile static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}}}
return instance;
}}

Scenario:
In Chocolate manufacturing industry, there are computer-controlled chocolate boilers. The job
of boiler is to take in milk and chocolate, bring them to boil and then pass it on to the next phase
of chocolate manufacturing process. We have to make sure that bad things don’t happen like
filling the filled boiler or boiling empty boiler or draining out unboiled mixture. We have to make
sure that there should be no simultaneous boiler activity taking place.

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 10

public class ChocolateBoiler {


private boolean empty;
private boolean boiled;
private static ChocolateBoiler uniqueins;

private ChocolateBoiler() {
empty=true;
boiled=false;
}
public static synchronized ChocolateBoiler getInstance() {
if(uniqueins==null) {
uniqueins=new ChocolateBoiler();
getInstance().fill();
getInstance().boil();
getInstance().drain();
}
return uniqueins;
}
public void fill() {
if(isempty()) {
empty=false;
empty=true;
}
}
public void drain() {
if(!isempty()&&isboiled()) {
empty=true;
}
}
public void boil() {
if(!isempty() && !isboiled()) {
boiled=true;
}
}
public boolean isempty() {
return empty;
}
public boolean isboiled() {
return boiled;
}
}
Virtual University of Pakistan | www.vumultan.com
CS711 – Software Design 11

Prototype Design Pattern


Intent:
To reuse already instantiated objects that has already performed time-consuming instantiation
process.

Shallow Copy
package ShallowCopy;
class Car {
private String name;
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Car(String s) {
name = s;
}
}

class Person implements Cloneable {


private Car car; //Lower-level object
private String name;
public Car getCar() {
return car;
}
Virtual University of Pakistan | www.vumultan.com
CS711 – Software Design 12

public String getName() {


return name;
}
public void setName(String s) {
name = s;
}
public Person(String s, String t) {
name = s;
car = new Car(t);
}
public Object clone() {
try { //shallow copy
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
public class ShallowTestCopy {
public static void main(String[] args) {
Person p = new Person("Person-A" ,"Civic"); //Original Object
System.out.println("Original (orginal values): " + p.getName());
System.out.println(p.getCar().getName());

Person q = (Person) p.clone(); //Clone as a shallow copy


System.out.println("Clone (before change): " + q.getName() + " - "
+ q.getCar().getName());
q.setName("Person-B"); //change the primitive member
q.getCar().setName("Accord"); //change the lower-level object
System.out.println("Clone (after change): " + q.getName() + " - "
+ q.getCar().getName());
System.out.println("Original (after clone is modified): " + p.getName() + " - "
+ p.getCar().getName());
}
}
OUTPUT
Original (orginal values): Person-A
Civic
Clone (before change): Person-A – Civic
Clone (after change): Person-B – Accord
Original (after clone is modified): Person-A – Accord
Virtual University of Pakistan | www.vumultan.com
CS711 – Software Design 13

Deep Copy
class Car {
private String name;
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Car(String s) {
name = s;
}
}

class Person implements Cloneable { //Lower-level object


private Car car;
private String name;
public Car getCar() {
return car;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Person(String s, String t) {
name = s;
car = new Car(t);
}
public Object clone() { //Deep copy
Person p = new Person(name, car.getName());
return p;
}
}

public class DeepTestCopy {


public static void main(String[] args) { //Original Object
Person p = new Person("Person-A", "Civic");
System.out.println("Original (orginal values): " +p.getName());
Virtual University of Pakistan | www.vumultan.com
CS711 – Software Design 14

System.out.println(p.getCar().getName());
Person q = (Person) p.clone(); //Clone as a shallow copy
System.out.println("Clone (before change): " + q.getName() + " - "
+ q.getCar().getName());
q.setName("Person-B"); //change the primitive member
q.getCar().setName("Accord"); //change the lower-level object
System.out.println("Clone (after change): " +q.getName() + " - "
+q.getCar().getName());
System.out.println("Original (after clone is modified): " + p.getName() + " - "
+ p.getCar().getName());
}
}
OUTPUT
Original (orginal values): Person-A
Civic
Clone (before change): Person-A - Civic
Clone (after change): Person-B - Accord
Original (after clone is modified): Person-A - Civic

Example:
A computer user in a typical organization is associated with a user account. A user account can
be part of one or more groups. Permissions on different resources (such as servers, printers, etc.)
are defined at the group level. A user gets all the permissions defined for all groups that his or
her account is part of. Let us build an application to facilitate the creation of user accounts.
For simplicity, let us consider only two groups — Supervisor and AccountRep —
representing users who are supervisors and account representatives, respectively and we have
defined permissions in text files for each user group.

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 15

public class AccountPrototypeFactory {


private UserAccount accountRep;
private UserAccount supervisor;
public AccountPrototypeFactory(UserAccount supervisorAccount, UserAccount arep) {
accountRep = arep;
supervisor = supervisorAccount;
}
public UserAccount getAccountRep() {
return (UserAccount) accountRep.clone();
}
public UserAccount getSupervisor() {
return (UserAccount) supervisor.clone();
}
}
public class AccountManager {
public static void main(String[] args) {
/*Create Prototypical Objects*/
Vector supervisorPermissions = getPermissionsFromFile("supervisor.txt");
UserAccount supervisor = new UserAccount();
supervisor.setPermissions(supervisorPermissions);
Vector accountRepPermissions = getPermissionsFromFile("accountrep.txt");
UserAccount accountRep = new UserAccount();
accountRep.setPermissions(accountRepPermissions);

AccountPrototypeFactory factory =
new AccountPrototypeFactory(supervisor, AccountRep);
/* Using protype objects to create clones of user accounts */
UserAccount newSupervisor = factory.getSupervisor();
// Cloning is performed using existing factory object
newSupervisor.setUserName("Ali");
newSupervisor.setPassword("canvas");
System.out.println(newSupervisor);
UserAccount anotherSupervisor = factory.getSupervisor();
anotherSupervisor.setUserName("Asim");
anotherSupervisor.setPassword("temp");
System.out.println(anotherSupervisor);
UserAccount newAccountRep = factory.getAccountRep();
newAccountRep.setUserName("Ahmad");
newAccountRep.setPassword("Pakistan");
System.out.println(newAccountRep);
}
Virtual University of Pakistan | www.vumultan.com
CS711 – Software Design 16

Builder Design Pattern


Intent:
• Defines an instance for creating an object but letting subclasses decide which class to instantiate
• Refers to the newly created object through a common interface.
• Separate the construction of a complex object from its representation so that the same
construction process can create different representations.

Example:
Consider construction of a home, Home is the final end product (object) that is to be returned as the
output of the construction process. It will have many steps, like basement construction, wall construction
and so on roof construction. Finally the whole home object is returned. Here using the same process you
can build houses with different properties. Each house is having same construction steps but the output
may be different depending upon the requirements of the house but the end product is home in any case.
We need to write programs which simulate this process.

package BuildingHouse;
public interface HousePlan {
public void setBasement(String basement);
public void setStructure(String structure);
public void setRoof(String roof);
public void setInterior(String interior);
}

public class House implements HousePlan {


private String basement;
private String structure;
private String roof;
private String interior;

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 17

public void setBasement(String basement) {


this.basement = basement;
}
public void setStructure(String structure) {
this.structure = structure;
}
public void setRoof(String roof) {
this.roof = roof;
}
public void setInterior(String interior) {
this.interior = interior;
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 18

public interface HouseBuilder {


public void buildBasement();
public void buildStructure();
public void bulidRoof();
public void buildInterior();
public House getHouse();
}

public class IglooHouseBuilder implements HouseBuilder {


private House house;
public IglooHouseBuilder() {
this.house = new House();
}
public void buildBasement() {
house.setBasement("Ice Bars");
}
public void buildStructure() {
house.setStructure("Ice Blocks");
}
public void buildInterior() {
house.setInterior("Ice Carvings");
}
public void bulidRoof() {
house.setRoof("Ice Dome");
}
public House getHouse() {
return this.house;
}
}
public class CivilEngineer {
private HouseBuilder houseBuilder;
public CivilEngineer(HouseBuilder houseBuilder){
this.houseBuilder = houseBuilder;
}
public House getHouse() {
return this.houseBuilder.getHouse();
}
public void constructHouse() {
this.houseBuilder.buildBasement();
this.houseBuilder.buildStructure();
this.houseBuilder.bulidRoof();
this.houseBuilder.buildInterior();
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 19

public class BuilderSample {


public static void main(String[] args) {
HouseBuilder iglooBuilder = new IglooHouseBuilder();
CivilEngineer engineer = new CivilEngineer(iglooBuilder);
engineer.constructHouse();
House house = engineer.getHouse();
System.out.println("Builder constructed: "+house);
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 20

Structural Design Pattern


Adapter or Wrapper Design Pattern
Intent:
• Convert the interface of a class into another interface clients expect.
• Adapter lets classes work together, that could not otherwise because of incompatible interfaces
• Keeping the client code intact we need to write a new class which will make use of services offered
by the class.

• Target - defines the domain-specific interface that Client uses. This class is visible to the client
and client will interact or pass request to this class.
• Adapter - adapts the interface Adaptee to the Target interface.
• Adaptee - defines an existing interface that needs adapting.
• Client - collaborates with objects conforming to the Target interface.

Public class EnumerationIterator Implements Iterator {


Enumeration enumeration;

Public Enumerationterator(Enumeration enumeration) {


This.enumeration = enumeration;
}
Public Boolean hasNext() {
Return enumeration.hasMoreElements();
}
Public Object next() {
Return enumeration nextElement();
}
Public void remove() {
Throw new UnsupportedOperationException();
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 21

Façade Design Pattern


Intent:
1. To provide a simple interface to use the complex sub systems to the users by keeping intact the
functionality of subsystems
2. Power of subsystems will still be there but there will simplify access to the underlying subsystems.

“Façade provides a unified interface to a set of interfaces in a subsystem. It defines a higher-level interface
which is easier to use”

Without Facade With Facade

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 22

The Principle of Least Knowledge (PLK)


• “Talk only to your immediate friends” OR
• “For an operation O on a class C, only operations on the following objects should be called:
itself, its parameters, objects it creates, or its contained instance objects”

Problem Statement:
For a typical online transaction oriented system, customer can perform transactions against an account
i-e Pay pal etc; credit card validators are used for verifying the creditionals of a client submitted by the
client for checkout purposes. Address of the customer is also stored and checked for data entry checks
for shipment purposes. Usually account, address and credit card subsystems works together to provide
the feature of online transaction.

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 23

Composite Design Pattern


Intent:
1. The intent of this pattern is to compose objects into tree structures to represent part-whole
hierarchies’ i-e Aggregation.
2. Composite lets clients treat individual objects and compositions of objects uniformly.

“Composite Design pattern allow us to compose objects into tree structures to represent whole-part
hierarchy. It let the client handle the composite and individual components in a uniform manner”

Example with Code:


Let us create an application to simulate the Windows/UNIX file system. The file system consists mainly of
two types of components — directories and files. Directories can be made up of other directories or files,
whereas files cannot contain any other file system component. In this aspect, directories act as
nonterminal nodes and files act as terminal nodes or leaf node of a tree structure. The client will be able
to calculate the size of file or folder irrespective of the internal representation of the storage mechanism.

package composite;
public abstract class FileSystemComponent {
String name;
public FileSystemComponent(String cName) {
name = cName;
}
public void addComponent(FileSystemComponent component) throws CompositeException {
throw new CompositeException("Invalid Operation. Not Supported");
}
public FileSystemComponent getComponent(int componentNum) throws CompositeException {
throw new CompositeException("Invalid Operation. Not Supported");
}
public abstract long getComponentSize();
} //End of class FileSystemComponent

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 24

public class FileComponent extends FileSystemComponent {


private long size;
public FileComponent(String cName, long sz) {
super(cName);
size = sz;
}
public long getComponentSize() {
return size;
}
} //End of class

package composite;
import java.util.Vector;
public class DirComponent extends FileSystemComponent {
Vector dirContents = new Vector();
//individual files/sub folders collection
public DirComponent(String cName) {
super(cName);
}
public void addComponent(FileSystemComponent fc) throws CompositeException {
dirContents.add(fc);
}
public FileSystemComponent getComponent(int location) throws CompositeException {
return (FileSystemComponent) dirContents.elementAt(location);
}
public long getComponentSize() {
long sizeOfAllFiles = 0;
Enumeration e = dirContents.elements();
while (e.hasMoreElements()) {
FileSystemComponent component = (FileSystemComponent) e.nextElement();
sizeOfAllFiles = sizeOfAllFiles + (component.getComponentSize());
}
return sizeOfAllFiles;
}
} //End of class

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 25

Sample File Structure Used in the Main Program


public class CompositeDemo {
public static final String SEPARATOR = ”, ";
public static void main(String[] args) {
FileSystemComponent mainFolder = new DirComponent("Year2000");
FileSystemComponent subFolder1 = new DirComponent("Jan");
FileSystemComponent subFolder2 = new DirComponent("Feb");
//creating files
FileSystemComponent folder1File1 = new FileComponent("Jan1DataFile.txt,”1000);
FileSystemComponent folder1File2 = new FileComponent("Jan2DataFile.txt”,2000);
FileSystemComponent folder2File1 = new FileComponent("Feb1DataFile.txt”,3000);
FileSystemComponent folder2File2 = new FileComponent("Feb2DataFile.txt”,4000);

try {
mainFolder.addComponent(subFolder1);
mainFolder.addComponent(subFolder2);
subFolder1.addComponent(folder1File1);
subFolder1.addComponent(folder1File2);
subFolder2.addComponent(folder2File1);
subFolder2.addComponent(folder2File2);
} catch (CompositeException ex) {
//
}
//Client refers to both composite & //individual components in a uniform manner

System.out.println (" Main Folder Size= " + mainFolder.getComponentSize() + "kb");


System.out.println(" Sub Folder1 Size= " + subFolder1.getComponentSize() + "kb");
System.out.println(" File1 in Folder1 size= " + folder1File1.getComponentSize() + "kb");
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 26

Flyweight Design Pattern


Intent:
To use sharing to support a large number of objects that have part of their internal state in common
where the other part of state can vary.

“Facilitates the reuse of many fine-grained objects, making the utilization of large numbers of objects
more efficient”

Description of Classes:
1. Flyweight - Declares an interface through which flyweights can receive and act on extrinsic state.
2. Concrete Flyweight - Implements the Flyweight interface and stores intrinsic state. A Concrete
Flyweight object must be sharable. The Concrete flyweight object must maintain state that it is
intrinsic to it, and must be able to manipulate state that is extrinsic.
3. Flyweight Factory - The factory creates and manages flyweight objects. In addition the factory
ensures sharing of the flyweight objects. The factory maintains a pool of different flyweight
objects and returns an object from the pool if it is already created, adds one to the pool and
returns it in case it is new.
4. Client - A client maintains references to flyweights in addition to computing and maintaining
extrinsic state

Example:
We need to design for a war game in which there is a large number of soldier objects; a soldier object
maintains the graphical representation of a soldier, soldier behavior such as motion, and firing weapons,
in addition soldier’s health and location on the war terrain. Creating a large number of soldier objects is a
necessity however it would incur a huge memory cost.
Note that although the representation and behavior of a soldier is the same their health and
location can vary greatly. The war game instantiates 5 Soldier clients, each client maintains its internal

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 27

state which is extrinsic to the soldier flyweight, although 5 clients have been instantiated only one
flyweight Soldier has been used.

package flyweight; /** Flyweight Interface */


public interface Soldier {
/** Move Soldier From Old Location to New Location
Note that soldier location is extrinsic to the SoldierFlyweight Implementation */

public void moveSoldier( int previousLocationX, int previousLocationY ,


int newLocationX ,int newLocationY );
}
public class SoldierImp implements Soldier {
/** Intrinsic State maintained by flyweight implementation, Solider Shape (graphical
represetation) how to display the soldier is up to the flyweight implementation */
private Object soldierGraphicalRepresentation;

/** Note that this method accepts soldier location. Soldier Location is Extrinsic and no
reference to previous location or new location is maintained inside the flyweight
implementation */
public void moveSoldier( int previousLocationX, int previousLocationY,
int newLocationX, int newLocationY) {

/** delete soldier representation from previous location then render soldier
representation in new location*/
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 28

public class SoldierFactory { /** Pool for one soldier only, if there are more soldier types
this can be an array or list or better a HashMap */
private static Soldier SOLDIER; /** * getFlyweight * @return */

public static Soldier getSoldier(){ // this is a singleton // if there is no soldier


//This is singleton Design pattern usesge
if(SOLDIER==null){ // create the soldier
SOLDIER = new SoldierImp();
} // return the only soldier reference return SOLDIER;
}
}

public class SoldierClient { /** This is the "Heavyweight" soldier object which is the client of the flyweight
soldier this object provides all soldier services and is used in the game */
private Soldier soldier = SoldierFactory.getSoldier(); /**Reference to the flyweight */
private int currentLocationX = 0; /** This state is maintained by the client */
private int currentLocationY=0; /** This state is maintained by the client */

public void moveSoldier(int newLocationX, int newLocationY) {


// here the actual rendering is handled by the flyweight object
// this object is responsible for maintaining the state
// that is extrinsic to the flyweight
soldier.moveSoldier(currentLocationX, currentLocationY, newLocationX, newLocationY);
currentLocationX = newLocationX;
currentLocationY = newLocationY;
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 29

Proxy or Surrogate Design Pattern

Intent
The intent of this pattern is to provide a Placeholder for an object to control references to it.

“Proxy design pattern provides a surrogate or placeholder for another object to control access to it”

The participant’s classes in the proxy pattern are:


1. Subject - Interface implemented by the RealSubject and representing its services. The interface
must be implemented by the proxy as well so that the proxy can be used in any location where
the RealSubject can be used.
2. Proxy -Maintains a reference that allows the Proxy to access the RealSubject. It implements the
same interface implemented by the RealSubject so that the Proxy can be substituted for the
RealSubject. It Controls access to the RealSubject and may be responsible for its creation and
deletion.
3. RealSubject - the real object that the proxy represents.

Example:
Consider an image viewer program that lists and displays high resolution photos. The program has to show
a list of all photos however it does not need to display the actual photo until the user selects an image
item from a list.

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 30

The code below shows the Image interface representing the Subject. The interface has a single method
showImage() that the Concrete Images must implement to render an image to screen.

package proxy;
public interface Image { /** * Subject Interface */
public void showImage();
}

public class ImageProxy implements Image { /** * Proxy */


private String imageFilePath; /** * Reference to RealSubject */
private Image proxifiedImage;

public ImageProxy(String imageFilePath) {


this.imageFilePath= imageFilePath;
}
// Override the interface class method.
public void showImage() {
// create the Image Object only when the image is required to be shown
proxifiedImage = new HighResolutionImage(imageFilePath);
// now call showImage on realSubject
proxifiedImage.showImage();
}
}

public class HighResolutionImage implements Image {


public HighResolutionImage(String imageFilePath) {
loadImage(imageFilePath);
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 31

private void loadImage(String imageFilePath) {


// load Image from disk into memory
// this is heavy and costly operation
}

// override the method of interface class


public void showImage() {
// Actual Image rendering logic
}
}

public class ImageViewer {


public static void main(String[] args) {

// assuming that the user selects a folder that has 3 images


//create the 3 images
Image highResolutionImage1 = new ImageProxy("sample/veryHighResPhoto1.jpeg");
Image highResolutionImage2 = new ImageProxy("sample/veryHighResPhoto2.jpeg");
Image highResolutionImage3 = new ImageProxy("sample/veryHighResPhoto3.jpeg");

// assume that the user clicks on Image one item in a list


// this would cause the program to call showImage() for that image only
// note that in this case only image one was loaded into memory
highResolutionImage1.showImage();

// consider using the high resolution image object directly


Image highResolutionImageNoProxy1 =
new HighResolutionImage("sample/veryHighResPhoto1.jpeg");
Image highResolutionImageNoProxy2 =
new HighResolutionImage("sample/veryHighResPhoto2.jpeg");
Image highResolutionImageBoProxy3 =
new HighResolutionImage("sample/veryHighResPhoto3.jpeg");

// assume that the user selects image two item from images list
highResolutionImageNoProxy2.showImage();

// note that in this case all images have been loaded into memory
// and not all have been actually displayed
// this is a waste of memory resources

}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 32

Behavioral Design Patterns:


Iterator Design Pattern or Well Managed Collection
Intent:
1. Allows a client object to access the contents of a container in a sequential manner, without
having any knowledge about the internal representation of its contents.
2. Client should not be involved in the internal traversal of the contents of the container.

“The Iterator Design pattern provides a way to access the element of aggregate object sequentially
without knowing its underlying representation”

1. Iterator: Define an interface for accessing and traversing elements


2. ConcreteIterator: Implements the Iterator interface, Keep track of the current position in the
traversal
3. Aggregate: Defines an interface for creating an Iterator object (a factory method!)
4. ConcreteAggregate: Implements the Iterator creation interface to return an instance of the
proper ConcreteIterator

Example:
This example is using a collection of books and it uses an iterator to iterate through the collection. The
problem is to store the books in the form of collection and then the items from the collections are needed
to be retrieved from the container consistently.

interface IIterator {
public boolean hasNext();
public Object next();
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 33

interface IContainer {
public IIterator createIterator();
}

class BooksCollection implements IContainer {


private String m_titles[] = {"Design Patterns","1","2","3","4"};

public IIterator createIterator() {


BookIterator result = new BookIterator();
return result;
}
}

private class BookIterator implements IIterator {


private int m_position;

public boolean hasNext() {


if (m_position < m_titles.length)
return true;
else
return false;
}

public Object next() {


if (this.hasNext())
return m_titles[m_position++];
else
return null;
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 34

Observer or Publish and Subscribe Design Pattern


Intent:
Define a one-to-many dependency between objects so that when one object changes state, all its
dependents are notified and updated automatically.

“This pattern defines a one-to-many relationship between objects so that when there is change in the
state of the one object it should be notified and automatically update it all dependent”.

1. Subject: This class will keep track of its observers and provides an interface for attaching and
detaching Observer objects
2. Observer: It defines an interface for update notification
3. Concrete Subject: As discussed, the object being observed will be object of this class, it stores state
of interest to Concrete Observer objects. Its responsibility includes sending a notification to its
observers when its state changes
4. ConcreteObserver: This is object of class who is observing the subject class i-e the observing object.
This class stores state that should stay consistent with the subject's by implementing the Observer
update interface to keep its state consistent with the subject's

public class ConcreteSubject extends Observable {


private String name; // To be observed
private float price;
public ConcreteSubject(String name, float price) {
this.name = name;
this.price = price;
System.out.println("ConcreteSubject created: " + name + " at “ + price);
}
public String getName() {
return name;
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 35

public float getPrice() {


return price;
}
public void setName (String name) {
this.name = name;
setChanged(); // Methods Implemented in Java
notifyObservers(name);
}
public void setPrice(float price) {
this.price = price;
setChanged();
notifyObservers(new Float(price));
}
}

public class NameObserver implements Observer { // An observer of name changes.


private String name;
public NameObserver() {
name = null;
System.out.println("NameObserver created: Name is " + name);
}
public void update(Observable obj, Object arg) {
if (arg instanceof String) {
name = (String)arg;
System.out.println("NameObserver: Name changed to " + name);
} else {
System.out.println("NameObserver: Some other change to subject!");
}
}
}

public class PriceObserver implements Observer { // An observer of price changes.


private float price;
public PriceObserver() {
price = 0;
System.out.println("PriceObserver created: Price is " + price);
}
public void update(Observable obj, Object arg) {
if (arg instanceof Float) {
price = ((Float)arg).floatValue();
System.out.println("PriceObserver: Price changed to " + price);
} else {
System.out.println(”PriceObserver: Some other change to subject!");
} }

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 36

public class TestObservers {


public static void main(String args[]) { // Create the Subject and Observers.
ConcreteSubject s = new ConcreteSubject("Corn Pops", 1.29f);
NameObserver nameObs = new NameObserver();
PriceObserver priceObs = new PriceObserver();

// Add those Observers!


s.addObserver(nameObs);
s.addObserver(priceObs);

// Make changes to the Subject.


s.setName(“Corn Flakes");
s.setPrice(4.57f);
s.setPrice(9.22f);
s.setName("Sugar Crispies");
}
}

Output of the Program

ConcreteSubject created: Corn Pops at 1.29


NameObserver created: Name is null
PriceObserver created: Price is 0.0
PriceObserver: Some other change to subject
NameObserver: Name changed to Corn Flakes
PriceObserver: Price changed to 4.58
NameObserver: Some other change to subject!
PriceObserver: Price changed to 9.22
NameObserver: Some other change to subject!
PriceObserver: Some other change to subject
NameObserver: Name changed to Sugar Crispies

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 37

Templet or Pattern Design Pattern


Intent:
1. Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
2. Template Method lets subclasses redefine certain steps of an algorithm without letting them to
change the algorithm's structure.

1. Abstract Class: This class defines abstract primitive operations that concrete subclasses define to
implement steps of an algorithm.
2. Concrete Class: This class implements the primitive operations to carry out subclass-specific steps
of the algorithm.

Example:
Lets' assume we have to develop an application for a travel agency. The travel agency is managing each
trip. All the trips contain common behavior but there are several packages. For example, each trip contains
the basic steps:
1. The tourists are transported to the holiday location by plane/train/ships.
2. Every day they are visiting some place.
3. They are returning back home.

Our task is to design and implement a system which should simulate the mentioned requirements.

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 38

public class Trip { // This method can’t be overridden by the sub class but we are calling abstract method inside it.
//This will keep intact the outline of the algorithm.
public final void performTrip() {
doComingTransport();
doDayA();
doDayB();
doDayC();
doReturningTransport
}
public abstract void doComingTransport();
public abstract void doDayA();
public abstract void doDayB();
public abstract void doDayC();
public abstract void doReturningTransport();
}
public class PackageA extends Trip {
public void doComingTransport(){
System.out.println("The tourists are comming by air ...");
}
public void doDayA() {
System.out.println("The tourists are visiting the garden ...");
}
public void doDayB() {
System.out.println("The tourists are going to the museum ...");
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 39

public void doDayC() {


System.out.println("The tourists are going to mountains ...");
}
public void doReturningTransport() {
System.out.println("The tourists are going home by air ...");
}
}

public class PackageB extends Trip {


public void doComingTransport() {
System.out.println("The tourists are comming by train ...");
}
public void doDayA() {
System.out.println("The tourists are visiting the mountain ...");
}
public void doDayB() {
System.out.println("The tourists are going to the olympic stadium ...");
}
public void doDayC() {
System.out.println("The tourists are going to zoo ...");
}
public void doReturningTransport() {
System.out.println("The tourists are going home by train ...");
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 40

Memento or Souvenir Design Pattern


Intent:
The intent of this pattern is to capture the internal state of an object without violating encapsulation and
thus providing a mean for restoring the object into initial state when needed.

1. Memento: This class stores internal state of the Originator object. The state can include any
number of state variables. The Memento must have two interfaces, an interface to the caretaker.
This interface must not allow any operations or any access to internal state stored by the memento
and thus honors encapsulation. The other interface is to the originator and allows the originator to
access any state variables necessary to for the originator to restore previous state.
2. Originator: It creates a memento object capturing the originators internal state; it then uses the
memento object to restore its previous state.
3. Caretaker: This class is responsible for keeping the memento. The memento is opaque to the
caretaker, and the caretaker must not operate on it.

Example:
Let's use a simple example in Java to illustrate this pattern. As it's a pattern used for undo frameworks, we'll
model a editor. First, the memento needs to be able to save editor contents, which will just be plain text:

public class EditorMemento { //Memento


private final String editorState;
public EditorMemento(String state) {
editorState = state;
}

public String getSavedState() {


return editorState;
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 41

// Now our Originator class, the editor, can use the memento:
//Originator Class

public class Editor { //state


public String editorContents;
public void setState(String contents) {
this.editorContents = contents;
}

public EditorMemento save() {


return new EditorMemento(editorContents);
}

public void restoreToState(EditorMemento memento) {


editorContents = memento.getSavedState();
}
}
// Anytime we want to save the state, we call the save() method, and an undo would call the restoreToState method.
Our caretaker can then keep track of all the memento's in a stack for the undo framework to work.

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 42

Command or Encapsulating Invocation Design Pattern


Intent:
1. To encapsulate a request in an object
2. To allow the parameterization of clients with different requests
3. To allow saving the request in a queue
4. Promote “invocation of a method on an object” to full object status

“It encapsulates a request as an object thereby letting you parameterize other objects with different
requests queue or log request and support undoable operations”

The classes participating in the pattern are:


1. Command - declares an interface for executing an operation
2. ConcreteCommand - extends the Command interface, implementing the Execute method by
invoking the corresponding operations on Receiver. It defines a link between the Receiver and the
action.
3. Client - creates a ConcreteCommand object and sets its receiver
4. Invoker - asks the command to carry out the request
5. Receiver - knows how to perform the operations

Example:
In stock exchange, the client creates some orders for buying and selling stocks (ConcreteCommands). Then
the orders are sent to the agent (Invoker). The agent takes the orders and place them to the StockTrade
system (Receiver). The agent keeps an internal queue with the order to be placed. Let's assume that the
StockTrade system is closed each Monday, but the agent accepts orders, and queue them to be processed
later on.

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 43

public interface Order {


public abstract void execute ( );
}

class StockTrade {
public void buy() {
System.out.println("You want to buy stocks");
}
public void sell() {
System.out.println("You want to sell stocks ");
}
}

class Agent {
private m_ordersQueue = new ArrayList();
public Agent() {
}
void placeOrder(Order order) {
ordersQueue.addLast(order);
order.execute(ordersQueue.getFirstAndRemove());
}
}

Virtual University of Pakistan | www.vumultan.com


CS711 – Software Design 44

class BuyStockOrder implements Order {


private StockTrade stock;
public BuyStockOrder ( StockTrade st) {
stock = st;
}
public void execute( ) {
stock . buy( );
}
}

class SellStockOrder implements Order {


private StockTrade stock;
public SellStockOrder ( StockTrade st) {
stock = st;
}
public void execute( ) {
stock . sell( );
}
}

public class Client {


public static void main(String[] args) {
StockTrade stock = new StockTrade();
BuyStockOrder bsc = new BuyStockOrder (stock);
SellStockOrder ssc = new SellStockOrder (stock);
Agent agent = new Agent();
agent.placeOrder(bsc); // Buy Shares
agent.placeOrder(ssc); // Sell Shares
}
}

Virtual University of Pakistan | www.vumultan.com

You might also like