0% found this document useful (0 votes)
32 views28 pages

Week 5

Uploaded by

jikeb70500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views28 pages

Week 5

Uploaded by

jikeb70500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

CT-365 SOFTWARE ENGINEERING

LECTURE 5

DESIGN PATTERNS – II

HUMA TABASSUM
LECTURER
DEPT. OF COMPUTER SCIENCE & INFORMATION TECHNOLOGY
NED UNIVERSITY OF ENGINEERING & TECHNOLOGY
2
Facade Pattern
• Facade pattern is a type of structural design pattern.
• GoF Definition
• Provide a unified interface to a set of interfaces in a subsystem. Facade defines a
higher-level interface that makes the subsystem easier to use.
• Concept
• Suppose that there is a complex system where multiple objects need to perform a
series of tasks, and you need to interact with the system.
• In a situation like this, facade can provide you a simplified interface that takes care of
everything (the creation of those objects, providing the correct sequence of tasks, etc.).
• As a result, instead of interacting with multiple objects in a complicated way, you just
interact with a single object.
• It is one of those patterns that supports loose coupling.
• Here you emphasize the abstraction and hide the complex details by exposing a simple
interface.
• As a result, the code becomes clearer and more attractive. 3
Real-World Example
• Suppose that you are going to organize a birthday party, and you plan to
invite 500 people.
• Nowadays, you can go to any party organizer and let them know the key
information—party type, the date and time, number of attendees, and
so forth.
• The organizer does the rest for you.
• You do not need to think about how the hall will be decorated, whether
attendees will get their food from a buffet table or be served by the
caterer, and so forth.
• So, you do not need to buy items from the store or decorate the party
hall yourself—you just pay the organizer and let them do the job
properly. 4
Computer-World Example
• Think about a situation where you use a method from a library (in the
context of a programming language).
• You do not care how the method is implemented in the library.
• You just call the method to experiment the easy usage of it.
• A facade simplifies the usage of external APIs by hiding the
complexities of authentication, request formatting, and response
parsing.
• It can combine multiple APIs into a single interface, streamlining
interactions and reducing code duplication.
• A facade can create a modern interface for older, less accessible
systems, facilitating their integration with newer components.
5
6
Illustration

7
Implementation
// RobotBody.java
package jdp2e.facade.demo;
//Instruction manual -how to destroy a robot
public class RobotBody { public static void destroyRobot() {
//Instruction manual -how to create a robot System.out.println("Refer the manual
public static void createRobot() { before destroying of a robot.");
System.out.println("Refer the manual }
before creation of a robot."); //Method to destroy hands of a robot
} public void destroyHands() {
//Method to create hands of a robot System.out.println("The robot's hands
public void createHands() { are destroyed.");
System.out.println("Hands manufactured."); }
} //Method to destroy remaining parts (other than
//hands) of a robot
//Method to create remaining parts (other than public void destroyRemainingParts() {
//hands) of a robot
public void createRemainingParts() { System.out.println("The robot’s remaining
parts are destroyed.");
System.out.println("Remaining parts }
(other than hands) are created.");
} }
8
//RobotColor.java // RobotFacade.java
package jdp2e.facade.demo; package jdp2e.facade.demo;
public class RobotColor { public class RobotFacade {
public void setDefaultColor() { RobotColor rColor;
System.out.println("This is steel color robot."); } RobotHands rHands ;
public void setGreenColor() { RobotBody rBody;
System.out.println("This is a green color robot."); } public RobotFacade() {
} rColor = new RobotColor();
rHands = new RobotHands();
// RobotHands.java
rBody = new RobotBody();
package jdp2e.facade.demo; }
public class RobotHands { //Constructing a Milano Robot
public void setMilanoHands() { public void constructMilanoRobot() {
System.out.println("The robot will have EH1 Milano hands."); } RobotBody.createRobot();
public void setRobonautHands() { System.out.println("Creation of a Milano Robot Start.");
System.out.println("The robot will have Robonaut hands."); } rColor.setDefaultColor();
public void resetMilanoHands() { rHands.setMilanoHands();
System.out.println("EH1 Milano hands are about to be destroyed."); } rBody.createHands();
public void resetRobonautHands() { rBody.createRemainingParts();
System.out.println("Robonaut hands are about to be destroyed."); } System.out.println(" Milano Robot Creation End.");
} System.out.println();
}
9
//Constructing a Robonaut Robot //Destroying a Robonaut Robot
public void constructRobonautRobot() { public void destroyRobonautRobot() {
RobotBody.createRobot(); RobotBody.destroyRobot();
System.out.println("Creation of a Robonaut Robot Start."); System.out.println("Initiating a Robonaut Robot’s
rColor.setDefaultColor(); destruction process.");
rHands.setRobonautHands(); rHands.resetRobonautHands();
rBody.createHands(); rBody.destroyHands();
rBody.createRemainingParts(); rBody.destroyRemainingParts();
System.out.println(" Robonaut Robot Creation End."); System.out.println("A Robonaut Robot is destroyed.");
System.out.println(); System.out.println();
} }
//Destroying a Milano Robot }
public void destroyMilanoRobot() {
RobotBody.destroyRobot();
System.out.println("Milano Robot's destruction
process is started.");
rHands.resetMilanoHands();
rBody.destroyHands();
rBody.destroyRemainingParts();
System.out.println("Milano Robot's destruction
process is over.");
System.out.println();
10
}
//Client code
//FacadePatternExample.java
package jdp2e.facade.demo;
public class FacadePatternExample {
public static void main(String[] args) {
System.out.println("***Facade Pattern Demo***\n");
//Creating Robots
RobotFacade milanoRobotFacade = new RobotFacade();
milanoRobotFacade.constructMilanoRobot();
RobotFacade robonautRobotFacade = new RobotFacade();
robonautRobotFacade.constructRobonautRobot();
//Destroying robots
milanoRobotFacade.destroyMilanoRobot();
robonautRobotFacade.destroyRobonautRobot();
}
}

11
Output
***Facade Pattern Demo***
Refer the manual before creation of a robot. Refer the manual before destroying of a robot.
Creation of a Milano Robot Start. Milano Robot's destruction process is started.
This is steel color robot. EH1 Milano hands are about to be destroyed.
The robot will have EH1 Milano hands. The robot's hands are destroyed.
Hands manufactured. The robot's remaining parts are destroyed.
Remaining parts (other than hands) are created. Milano Robot's destruction process is over.
Milano Robot Creation End. Refer the manual before destroying of a robot.
Refer the manual before creation of a robot. Initiating a Robonaut Robot's destruction process.
Initiating the creational process of a Robonaut Robot. Robonaut hands are about to be destroyed.
This is a green color robot. The robot's hands are destroyed.
The robot will have Robonaut hands. The robot's remaining parts are destroyed.
Hands manufactured. A Robonaut Robot is destroyed
Remaining parts (other than hands) are created.
A Robonaut Robot is created. 12
Discussion
• In this implementation, you create some robots, and later, you destroy those
objects. (The word “destroy” is not used in the context of garbage collection in
this example).
• Here you can construct or destroy a particular kind of robot by invoking simple
methods like constructMilanoRobot() and destroyMilanoRobot() of the
RobotFacade class.
• From a client’s point of view, he/she needs to interact only with the facade (see
FacadePatternExample.java).
• RobotFacade is taking full responsibility in creating or destroying a particular kind
of robot.
• This facade is talking to each of the subsystems (RobotHands, RobotBody,
RobotColor) to fulfill the client’s request.
• The RobotBody class includes two simple static methods that provide instructions
prior to the creation or destruction of a robot.
• So, in this implementation, the clients do not need to worry about the creation of
the separate classes and the calling sequence of the methods. 13
14
Benefits Downsides
• Minimizes complexity of sub- • Complex implementation (especially
systems. with existing code).

• Aids principle of loose coupling. • Approach is coupled to an


additional level of indirection.
• Software becomes more flexible
and easily expandable. • High degree of dependence at
facade interface.

15
Template Pattern
• Template pattern is a type of behavioral design pattern.
• Behavioral patterns provide solution for the better interaction between
objects, how to provide lose coupling, and flexibility to extend easily in future.
• GoF Definition
• Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
Template method lets subclasses redefine certain steps of an algorithm without
changing the algorithm’s structure.
• Concept
• In a template method, you define the minimum or essential structure of an algorithm.
• Then you defer some responsibilities to the subclasses.
• The key intent is that you can redefine certain steps of an algorithm, but those changes
should not impact the basic flow of the algorithm.
• So, this design pattern is useful when you implement a multistep algorithm and you
want to allow customization through subclasses. 16
Real-World Example
• Suppose that you are ordering a pizza from a restaurant.
• For the chef, the basic preparation of the pizza is the same; he
includes some final toppings based on customer choice.
• For example, you can opt for a veggie pizza or a non-veggie pizza.
• You can also choose toppings like onions, extra cheese, mushrooms,
and so forth.
• The chef prepares the final product according to your preferences.

17
Computer-World Example
• Suppose that you are making a program to design engineering courses.
• Let’s assume that the first semester is common for all streams.
• In subsequent semesters, you need to add new papers/subjects to the
application based on the course.
• You see a similar situation in the upcoming illustration.
• Remember that this pattern makes sense when you want to avoid
duplicate codes in your application.
• At the same time, you may want to allow subclasses to change some
specific details of the base class workflow to provide varying behaviors
in the application.
18
19
Illustration

20
Implementation
package jdp2e.templatemethod.demo; private void completeMath() {
abstract class BasicEngineering { System.out.println("1.Mathematics");
}
//Making the method final to prevent overriding.
private void completeSoftSkills() {
public final void completeCourse() {
System.out.println("2.SoftSkills");
//The course needs to be completed in }
// the following sequence
public abstract void completeSpecialPaper();
//1.Math-2.SoftSkills-3.Special Paper
}
//Common Papers:
completeMath();
class ComputerScience extends BasicEngineering {
completeSoftSkills();
@Override
//Specialization Paper:
public void completeSpecialPaper() {
completeSpecialPaper();
System.out.println("3.Object-Oriented Programming");
}
}
} 21
class Electronics extends BasicEngineering {
@Override
public void completeSpecialPaper() {
System.out.println("3.Digital Logic and Circuit Theory");
}
}

public class TemplateMethodPatternExample {


public static void main(String[] args) {
System.out.println("***Template Method Pattern Demo***\n");
BasicEngineering preferrredCourse = new ComputerScience();
System.out.println("Computer Sc. course will be completed in following order:");
preferrredCourse.completeCourse();
System.out.println();
preferrredCourse = new Electronics();
System.out.println("Electronics course will be completed in following order:");
preferrredCourse.completeCourse();
}
} 22
Output
***Template Method Pattern Demo***
Computer Sc. course will be completed in following order:
1.Mathematics
2.SoftSkills
3.Object-Oriented Programming
Electronics course will be completed in following order:
1.Mathematics
2.SoftSkills
3.Digital Logic and Circuit Theory

23
Discussion
• In the following implementation, it is assumed that each engineering
student needs to complete the course of Mathematics and then Soft skills
• (This subject may deal with communication skills, character traits, people
management skills etc.) in their initial semesters to obtain the degree.
• Later you will add special paper/s to these courses (Computer Science or
Electronics).
• To serve the purpose, a method completeCourse() is defined in an abstract
class BasicEngineering.
• The method has been marked as final, so that subclasses of
BasicEngineering cannot override the completeCourse() method to alter
the sequence of course completion order.
• Two other concrete classes – ComputerScience and Electronics are the
subclasses of BasicEngineering class and they are completing the abstract
method completeSpecialPaper() as per their needs. 24
25
Benefits Downsides
• Code Reusability: The template • Flexibility Constraints: The template
method encapsulates the algorithm’s method delineates a fixed structure,
structure, fostering code reuse potentially curtailing flexibility. Any
across diverse subclasses. deviation mandates adjustments to
• Consistent Algorithmic Structure: It the template method.
ensures a uniform structure for the • Complexity Concerns: As the
algorithm, minimizing redundancy number of steps and variations
and fostering maintainability. burgeons, the pattern can burgeon
• Extension without Modification: into complexity, potentially
Subclasses can extend the algorithm challenging maintainability.
without altering the template
method, providing a robust
extension mechanism. 26
27
28

You might also like