You are on page 1of 35

Practical Workbook

CS-325
Software Development and Testing

Name : _____________________________
Year : _____________________________
Batch : _____________________________
Roll No : _____________________________
Department: _____________________________

Department of Computer & Information Systems Engineering


NED University of Engineering & Technology
Practical Workbook
CS-325
Software Development and Testing

Prepared by:

Ms. Fakhra Aftab, Ms. Ramish Fatima, Ms. Ibshar Ishrat

February 2021
INTRODUCTION
This workbook has been compiled to assist the conduct of practical classes for CS-325 Software Design
and Testing. Practical work relevant to this course aims at providing students a chance to explore advanced
processes and methods for developing and testing software systems using sound engineering principles.

The Course Profile of CS-325 Software Design and Testing lays down the following Course Learning
Outcome:
“Explore modern techniques for software development and testing”

All lab sessions of this workbook have been designed to assist the achievement of the above CLO. A rubric
to evaluate student performance has been provided at the end of the workbook.

Lab session 1 covers various software verification and validation techniques. Lab sessions 2 till 4 cover
various types of structural design patterns. Lab session 5 demonstrates the usage of behavioral design
patterns in various software systems. Design patterns are used to provide generalized solution to develop
complex software systems. Lab session 6 deals with usage of tool for formal specification in Requirement
Engineering. It helps to provide consistency and completeness in the requirement specification document.
Lab session 7 and 8 target the design flow mechanism for embedded/IoT based systems. Lab session 9
covers the latest techniques for quality reviews in Software Development Life Cycle. Lab session 10 aims
to cover various testing methodologies for object-oriented applications. Lab session 11 till 13 demonstrates
the usage of testing tools for the validation of web applications, mobile applications and APIs respectively.
Lab session 14 discusses Complex Engineering Activity.

This workbook is designed to equally assist instructor and student, practically realizing theoretical concepts
of the course, and providing in-depth understanding and elaborate development & testing experience.
CONTENTS

Lab Teacher’s Date


Title Page# Signature
Session#
Use various programs testing techniques verification & validation
1. techniques in agile software design and development
1

Practice Adapter Design Pattern to relate different interfaces in a


2. software system
5

Explore Structural Design Pattern to add functionality to an object


3. dynamically
11

4. Use Façade Design Pattern to simplify a complex software system 17

5. Practice different types of Behavioral Design Patterns 23

Practice Formal Method’s tool to achieve preciseness in software


6. specification document

7. Explore Internet–of-things (IoT) design flow and patterns

Practice the use of specified design patterns to implement


8. embedded/IoT systems application efficiently

9. Explore automated quality reviews in SDLC

10. Practice testing of object-oriented applications

11. Use any latest tool for testing Web applications/CSS Validation

12. Explore any latest mobile application testing tool

Use any latest APIs testing tool to validate the correctness of


13. responses and data

14. Complex Engineering Activity

Rubrics
Software Design and Testing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 01

Use various verification & validation techniques in agile software design and
development

Verification involves the set of activities to ensure that software correctly implements a specific function and
conforms to its specification. These activities take place at each stage of the software process.

Validation is a generic process and involves different sets of activities to ensure that the developed software is
traceable to customer requirements. It ensures that the software meets customer's expectations.

Software Testing is a method to check whether the actual software product matches expected requirements and to
ensure that software product is defect free. It involves execution of software/system components using manual or
automated tools to evaluate one or more properties of interest. The purpose of software testing is to identify errors,
gaps or missing requirements in contrast to actual requirements.

Software Testing is important because if there are any bugs or errors in the software, it can be identified early and
can be solved before delivery of the software product. Properly tested software product ensures reliability, security
and high performance which further results in time saving, cost effectiveness and customer satisfaction.

Black Box Method for testing Functional Requirements

Internal system design is not considered in this type of testing. Tests are based on the requirements and functionality.

1. Boundary Value Testing:

This type of testing checks the behavior of the application at the boundary level. It is performed for checking if
defects exist at boundary values. Boundary Value Testing is used for testing a different range of numbers. There is
an upper and lower boundary for each range and testing is performed on these boundary values.
If testing requires a test range of numbers from 1 to 500 then Boundary Value Testing is performed on values at 0,
1, 2, 499, 500 and 501.

2. Equivalence Partitioning:

It is a testing technique and a type of Black Box Testing. During this Equivalence Partitioning, a set of the group is
selected and a few values or numbers are picked up for testing. It is understood that all values from that group generate
the same output.
The aim of this testing is to remove redundant test cases within a specific group which generates the same output but
not any defect.
Suppose, the application accepts values between -10 to +10 so using equivalence partitioning the values picked up
for testing are zero, one positive value, one negative value. So the Equivalence Partitioning for this testing is -10 to
-1, 0, and 1 to 10.

1
Software Design and Testing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Test Case Template

Several standard fields of a sample Test Case template are listed below:
Test case ID: Unique ID is required for each test case. Follow some convention to indicate the types of the test. For
Example, ‘TC_UI_1’ indicating ‘user interface test case #1’.
Test priority (Low/Medium/High): This is very useful while test execution. Test priority for business rules and
functional test cases can be medium or higher whereas minor user interface cases can be of a low priority. Test
priority should always be set by the reviewer.
Module Name: Mention the name of the main module or the sub-module.
Test Designed By Name of the Tester.
Test Designed Date: Date when it was written.
Test Executed By: Name of the Tester who executed this test. To be filled only after test execution.
Test Execution Date: Date when the test was executed.
Test Title/Name: Test case title. For Example, verify the login page with a valid username and password.
Test Summary/Description: Describe the test objective in brief.
Pre-conditions: Any prerequisite that must be fulfilled before the execution of this test case. List all the pre-
conditions in order to execute this test case successfully.
Dependencies: Mention any dependencies on the other test cases or test requirements.
Test Steps: List all the test execution steps in detail. Write test steps in the order in which they should be executed.
Make sure to provide as many details as you can.
Test Data: Use of test data as an input for this test case. You can provide different data sets with exact values to be
used as an input.
Expected Result: What should be the system output after test execution? Describe the expected result in detail
including message/error that should be displayed on the screen.
Post-condition: What should be the state of the system after executing this test case?
Actual result: The actual test result should be filled after test execution. Describe the system behavior after test
execution.
Status (Pass/Fail): If an actual result is not as per the expected result, then mark this test as failed. Otherwise, update
it as passed.

Figure 1.1 Test Case Template

2
Software Design and Testing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Test Driven Development

Test Driven Development (TDD) is a software development approach in which test cases are developed to specify
and validate what the code will do. In simple terms, test cases for each functionality are created and tested first and
if the test fails then the new code is written in order to pass the test and make code simple and bug-free.
Test-Driven Development starts with designing and developing tests for every small functionality of an application.
TDD instructs developers to write new code only if an automated test has failed. This avoids duplication of code.
Following steps define how to perform TDD test:

1. Add a test.
2. Run all tests and see if any new test fails.
3. Write some code.
4. Run tests and Refactor code.
5. Repeat.

Exercises

1. Find suitable black-box test data for each of the following. Also prepare the complete Test Case Document
(Attach print outs):
a. A program that implements an eight function calculator. It takes the operation to be performed and
parameters as input from the user.
b. A program that inputs an array of 10 integers from the user & sorts it in descending order.
2. Write a program for a 3x3 matrix multiplication. Supply suitable test data. Also inspect various reasons for
program failure.
3. Provide code snippets & design tests only for valid equivalence partitions and boundary values for the
following:
a) A switch is turned off when temperature falls below 18 and it turns on when it is above 21.
b) Order numbers in a stock control system range from 10000 to 99999 inclusive.
4. Use Test Driven Development approach for the implementation of Linked List Class in java. Report your
findings.

3
Software Design and Testing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Printouts:

4
Software Design and Testing Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 02
Practice Adapter Design Pattern to relate different interfaces in a software system
Adapter Design Pattern is a structural design pattern that allows two unrelated interfaces to work together. It makes
two incompatible interfaces compatible without changing their existing code. Adapter patterns use a single class (the
adapter class) to join functionalities of independent or incompatible interfaces/classes.

This pattern is easy to understand as the real world is full of adapters. For example, consider a USB to HDMI adapter.
We need this when we have an HDMI interface on one end and USB on the other. Since they are incompatible with
each other, we use an adapter that converts one to other. Adapters are used when we have a class (Client) expecting
some type of object and we have an object (Adaptee) offering the same features but exposing a different interface.

To use an adapter:

• The client makes a request to the adapter by calling a method on it using the target interface.
• The adapter translates that request on the adaptee using the adaptee interface.
• Client receives the results of the call and is unaware of adapter’s presence.

The adapter pattern converts the interface of a class into another interface clients expect. Adapter lets classes work
together that couldn’t otherwise because of incompatible interfaces.

Class Diagram:

Figure 2.2 Adapter Design Pattern

The client sees only the target interface and not the adapter. The adapter implements the target interface. Adapter
delegates all requests to Adaptee.
Example:
Suppose you have a Bird class with fly() , and makeSound() methods. And also a ToyDuck class with squeak()
method. Let’s assume that you are short on ToyDuck objects and you would like to use Bird objects in their place.

5
Software Design and Testing Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Birds have some similar functionality but implement a different interface, so we can’t use them directly. So we will
use adapter pattern. Here our client would be ToyDuck and adaptee would be Bird.

Below is Java implementation of it.

Step 1: Create Bird.java and ToyDuck.java interfaces

interface Bird
{
// birds implement Bird interface that allows
// them to fly and make sounds adaptee interface
public void fly();
public void makeSound();
}

interface ToyDuck
{
// target interface
// toyducks dont fly they just make
// squeaking sound
public void squeak();
}

Step 2: Create concrete classes implementing the interfaces


class Sparrow implements Bird
{
// a concrete implementation of bird
public void fly()
{
System.out.println("Flying");
}
public void makeSound()
{
System.out.println("Chirp Chirp");
}
}

class PlasticToyDuck implements ToyDuck


{
public void squeak()
{
System.out.println("Squeak");
}
}

Step 3: Create the adapter class implementing the adaptee interface

class BirdAdapter implements ToyDuck


{
// You need to implement the interface your
// client expects to use.
Bird bird;

6
Software Design and Testing Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

public BirdAdapter(Bird bird)


{
// we need reference to the object we
// are adapting
this.bird = bird;
}

public void squeak()


{
// translate the methods appropriately
bird.makeSound();
}
}

Step 4: Create the main class demonstrating the adapter design pattern

class Main
{
public static void main(String args[])
{
Sparrow sparrow = new Sparrow();
ToyDuck toyDuck = new PlasticToyDuck();

// Wrap a bird in a birdAdapter so that it


// behaves like toy duck
ToyDuck birdAdapter = new BirdAdapter(sparrow);

System.out.println("Sparrow...");
sparrow.fly();
sparrow.makeSound();

System.out.println("ToyDuck...");
toyDuck.squeak();

// toy duck behaving like a bird


System.out.println("BirdAdapter...");
birdAdapter.squeak();
}
}

7
Software Design and Testing Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Exercise

1. Develop a simple calculator following the Adapter Design Pattern.


2. Provide the code for the following diagram:

Figure 2.2 Adapter Pattern Example

8
Software Design and Testing Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Printouts:

9
Software Design and Testing Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

10
Software Design and Testing Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 03
Explore Structural Design Pattern to add functionality to an object dynamically.

The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible
alternative to sub-classing for extending functionality.

Decorators have the same super-type as the objects they decorate. One can use one or more decorators to wrap an
object. Given that the decorator has the same super-type as the object it decorates, we can pass around a decorated
object in place of the original (wrapped) object. The decorator adds its own behavior either before and/or after
delegating to the object it decorates to do the rest of the job. Objects can be decorated at any time, so we can decorate
objects dynamically at runtime with as many decorators as we like.

Class Diagram:

Figure 3.1 Decorator Design Pattern

The ConcreteComponent class is the one for which we’ll like add additional behaviors at runtime. The
ConcreteDecorator1, ConcreteDecorator2 are the decorator classes which hold the logic to decorate a given
Component.
Note that the abstract Decorator class has a Component. In other words, it aggregates any other type of component
which allows us to stack components one on the top of the other.
Moreover, both the ConcreteComponent and Decorator classes implement a common interface – Component.

11
Software Design and Testing Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Example
We are going to create a Shape interface and concrete classes implementing the Shape interface. We will then
create an abstract decorator class ShapeDecorator implementing the Shape interface and having Shape object as its
instance variable.
RedShapeDecorator is concrete class implementing ShapeDecorator.
DecoratorPatternDemo, our demo class will use RedShapeDecorator to decorate Shape objects.

Class diagram

Figure 3.2 Class Diagram

Implementation code
Step 1: Shape.java interface

package decorator_pattern;

public interface Shape {


void draw ();
}
Step 2: Create concrete classes implementing the interface Shape
package decorator_pattern;

public class Circle implements Shape {


@Override
public void draw() {
System.out.println("Shape: Circle");
}
}

package decorator_pattern;

public class Rectangle implements Shape{

12
Software Design and Testing Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}

Step 3: Create the abstract decorator class implementing the Shape interface

package decorator_pattern;

public abstract class ShapeDecorator implements Shape {


protected Shape decoratedShape;

public ShapeDecorator(Shape decoratedShape){


this.decoratedShape = decoratedShape;
}

public void draw(){


decoratedShape.draw();
}}
Step 4: Create concrete class implementing the ShapeDecorator abstract class

package decorator_pattern;

public class RedShapeDecorator extends ShapeDecorator {


public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}

@Override
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}

private void setRedBorder(Shape decoratedShape){


System.out.println("Border Color: Red");
}
}
Step 4: Create the main class demonstrating the decorator design pattern

package decorator_pattern;

public class Demo {

public static void main(String[] args) {


// TODO Auto-generated method stub
Shape circle = new Circle();

Shape redCircle = new RedShapeDecorator(new Circle());

Shape redRectangle = new RedShapeDecorator(new Rectangle());


System.out.println("Circle with normal border");
circle.draw();

System.out.println("\nCircle of red border");


redCircle.draw();

System.out.println("\nRectangle of red border");

13
Software Design and Testing Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

redRectangle.draw();
}

}
Exercise

1. Suppose we are selling a gift item. Once a user selects a gift item, there can be multiple ways just to decorate
that gift item with a red or a blue ribbon, purple or green gift wrap, etc. Draw a class diagram for this scenario
using a decorator pattern. Also implement an interface for gift items and use decorator patterns to execute
different combinations possible using Java. Also attach print outs.

2. Suppose you are planning to start a side business of a Coffee Shop. To automate the order processing, you
intend to seek help from the OO decorator pattern. Create a Beverage class and decorate it with condiments
at run time and estimate the overall cost of Beverage at the end. For example, a customer wants Espresso
with mocha and whip or he wants Hot Chocolate with Vanilla ice cream. Draw a class diagram for the given
situation and implement it in Java. Also attach print outs.

14
Software Design and Testing Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Printouts:

15
Software Design and Testing Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

16
Software Design and Testing Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 04
Use Façade Design Pattern to simplify a complex software system
Façade Design Pattern is a structural design pattern that hides the complexities of the system and provides an
interface to the client from where the client can access the system.

Figure 4.1 Façade Design Pattern

Example

Let's look at a simple implementation that allows the Client to view Upperbody and LowerBody workouts in a
Gymnasium.

Step 1: Create the Workout interface.

public interface Workout {


void setWorkout();
void viewWorkout();
}

Step 2: Create a simple Exercise class that contains an id and name. This is to store the exercises as an
object.

public class Exercise {


private int id;
private String name;
public Exercise(int id, String name) {

17
Software Design and Testing Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}

Step 3: Create the Concrete classes LowerBody and UpperBody that inherit Workout.

In the setWorkout method we are adding hard coded exercises to a list. In viewWorkout(), we run an enhanced for
loop and print out the Exercises names.

import java.util.ArrayList;
import java.util.List;
public class LowerBody implements Workout {
private List<Exercise> exercises = new ArrayList<>();
/**
* Add lower body exercises to an ArrayList
*/
@Override
public void setWorkout() {
exercises.add(new Exercise(1, "Squats"));
exercises.add(new Exercise(2, "Calf raises"));
exercises.add(new Exercise(3, "Lunges"));
}
/**
* Loop through the list of exercises and print them out
*/
@Override
public void viewWorkout() {
System.out.println("LowerBody Workout");
for(Exercise exercise : exercises){
System.out.println("Exercise: " + exercise.getName());
}
}

import java.util.ArrayList;
import java.util.List;
public class UpperBody implements Workout {
private List<Exercise> exercises = new ArrayList<>();
/**

18
Software Design and Testing Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

* Add upper body exercises to an ArrayList


*/
@Override
public void setWorkout() {
exercises.add(new Exercise(1, "Bench Press"));
exercises.add(new Exercise(2, "Push Ups"));
exercises.add(new Exercise(3, "Inline Bench Press"));
}
/**
* Loop through the list of Exercises and print them out
*/
@Override
public void viewWorkout() {
System.out.println("UpperBody Workout");
for(Exercise exercise : exercises){
System.out.println("Exercise: " + exercise.getName());
}
}
}

Step 4: Create the WorkoutFacade class that will hide all of the logic from the Client

Here we create viewUpperBodyWorkout and viewLowerBodyWorkout that will


call setWorkout and viewWorkout. The client does not access Workout, UpperBody, or LowerBody.

public class WorkoutFacade {


/**
* Creates an instance of UpperBody and calls setWorkout() and viewWorkout()
*/
public void viewUpperBodyWorkout() {
Workout workout = new UpperBody();
workout.setWorkout();
workout.viewWorkout();
}
/**
* Creates an instance of LowerBody and calls setWorkout() and viewWorkout()
*/
public void viewLowerBodyWorkout() {
Workout workout = new LowerBody();
workout.setWorkout();
workout.viewWorkout();
}
}
Step 5: Create the WorkoutClient

19
Software Design and Testing Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

We create an instance of WorkoutFacade and call viewUpperBodyWorkout() and viewLowerBodyWorkout(). This


will produce the following output.

public class WorkoutClient {


public static void main(String[] args){
WorkoutFacade workoutFacade = new WorkoutFacade();
workoutFacade.viewUpperBodyWorkout();
System.out.println();
workoutFacade.viewLowerBodyWorkout();
}
}

Step 6: Last but not the least, verify the output.

UpperBody Workout
Exercise: Bench Press
Exercise: Push Ups
Exercise: Inline Bench Press

LowerBody Workout
Exercise: Squats
Exercise: Calf raises
Exercise: Lunges

EXERCISES
1. Implement the façade design pattern for the diagram given below:

Figure 4.2 Façade Pattern Example

2. For a library system, there are three classes namely Fiction, Non Fiction and Technology. All of these
classes consists of getBookList() method to get the books of the respective genre. All of these class

20
Software Design and Testing Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

implement BookGenre interface. Implement a façade of LibraryService containing a method of


BookBorrow(). Also demonstrate the working of façade using a client.

Printouts:

21
Software Design and Testing Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

22
Software Design and Testing Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 05
Practice different types of Behavioral Design Patterns
In software engineering, behavioral design patterns are design patterns that identify common communication
patterns among objects. By doing so, these patterns increase flexibility in carrying out communication. Behavioral
patterns are concerned with the assignment of responsibilities between objects, or, encapsulating behavior in an object
and delegating requests to it.

In this lab we are going to cover three types of behavioral patterns

a) Template design pattern


b) State design pattern
c) Command design pattern

The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to
subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s
structure.

This pattern is all about creating a template for an algorithm. A template is just a method; more specifically, it’s a
method that defines an algorithm as a set of steps. One or more of these steps is defined to be abstract and
implemented by a subclass. This ensures the algorithm’s structure stays unchanged, while subclasses provide some
part of the implementation.

Template method should consist of certain steps whose order is fixed and for some of the methods, implementation
differs from base class to subclass. Template method should be final.

Most of the time, subclasses call methods from superclass but in template pattern, superclass template method calls
methods from subclasses.

Methods in base class with default implementation are referred as Hooks and they are intended to be overridden by
subclasses, if you want some of the methods to be not overridden, you can make them final.

Class Diagram:

Figure 5.1

23
Software Design and Testing Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Example
We are going to create a Game abstract class defining operations with a template method set to be final so that it
cannot be overridden. Cricket and Football are concrete classes that extend Game and override its methods.

TemplatePatternDemo, our demo class, will use Game to demonstrate use of template pattern.

Class diagram

Figure 5.2

Step1: Create an abstract class with a template method being final.

Game.java

public abstract class Game {


abstract void initialize();
abstract void startPlay();
abstract void endPlay();

//template method
public final void play(){

//initialize the game


initialize();

//start game
startPlay();

//end game
endPlay();
}

24
Software Design and Testing Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Step 2: Create concrete classes extending the above class.

Cricket.java

public class Cricket extends Game {

@Override
void endPlay() {
System.out.println("Cricket Game Finished!");
}

@Override
void initialize() {
System.out.println("Cricket Game Initialized! Start playing.");
}

@Override
void startPlay() {
System.out.println("Cricket Game Started. Enjoy the game!");
}
}

Football.java
public class Football extends Game {

@Override
void endPlay() {
System.out.println("Football Game Finished!");
}

@Override
void initialize() {
System.out.println("Football Game Initialized! Start playing.");
}

@Override
void startPlay() {
System.out.println("Football Game Started. Enjoy the game!");
}
}

Step 3: Use the Game's template method play() to demonstrate a defined way of playing game.

TemplatePatternDemo.java

public class TemplatePatternDemo {


public static void main(String[] args) {

25
Software Design and Testing Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Game game = new Cricket();


game.play();
System.out.println();
game = new Football();
game.play();
}
}

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to
change its class.
The pattern encapsulates state into separate classes and delegates to the object representing the current state, we know
that behavior changes along with the internal state. If an object you’re using can completely change its behavior, then
it appears to you that the object is actually instantiated from another class. In reality, however, you know that we are
using composition to give the appearance of a class change by simply referencing different state objects.

Class diagram

Figure 5.3

Example
We are going to create a State interface defining an action and concrete state classes implementing the State interface.
Context is a class which carries a State.StatePatternDemo, our demo class, will use Context and state objects to
demonstrate change in Context behavior based on type of state it is in.

Class diagram

Figure 5.4

Step 1: Create an interface

26
Software Design and Testing Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

State.java

public interface State {


public void doAction(Context context);
}
Step 2: Create concrete classes implementing the same interface

StartState.java

public class StartState implements State {

public void doAction(Context context) {


System.out.println("Player is in start state");
context.setState(this);
}

public String toString(){


return "Start State";
}
}

StopState.java

public class StopState implements State {

public void doAction(Context context) {


System.out.println("Player is in stop state");
context.setState(this);
}

public String toString(){


return "Stop State";
}
}

Step 3: Create Context Class

Context.java

public class Context {


private State state;

public Context(){
state = null;
}

public void setState(State state){


this.state = state;
}

public State getState(){


return state;
}

27
Software Design and Testing Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

}
Step 4: Use the Context to see change in behaviour when State changes

StatePatternDemo.java

public class StatePatternDemo {


public static void main(String[] args) {
Context context = new Context();

StartState startState = new StartState();


startState.doAction(context);

System.out.println(context.getState().toString());

StopState stopState = new StopState();


stopState.doAction(context);

System.out.println(context.getState().toString());
}
}

The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with
different requests, queue or log requests, and support undoable operations.

Command decouples the object that invokes the operation from the one that knows how to perform it. To achieve
this separation, the designer creates an abstract base class that maps a receiver (an object) with an action (a pointer
to a member function). The base class contains an execute () method that simply calls the action on the receiver.

All clients of Command objects treat each object as a "black box" by simply invoking the object's virtual execute ()
method whenever the client requires the object's "service".

A Command class holds some subset of the following: an object, a method to be applied to the object, and the
arguments to be passed when the method is applied. The Command's "execute" method then causes the pieces to
come together.

Sequences of Command objects can be assembled into composite (or macro) commands.

Class Diagram

28
Software Design and Testing Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Figure 5.5

Exercises

1. Suppose we want to provide an algorithm to build a house. The steps needed to be performed to build a house
are – building foundation, building pillars, building walls and windows. The important point is that we can’t
change the order of execution because we can’t build windows before building the foundation. So in this case we
can create a template method that will use different methods to build the house. Now building the foundation for
a house is the same for all types of houses, whether it is a wooden house or a glass house. So we can provide
base implementation for this, if subclasses want to override this method, they can but mostly it’s common for all
the types of houses. To make sure that subclasses don’t override the template method, we should make it final.
Draw class diagram and implement them using template design pattern. Attach printouts.

2. Implement the operation of a Vending Machine using an appropriate design pattern in Java. Also draw the class
diagram and attach printouts. Initially the machine is idle. Once the customer arrives he can purchase either a
chocolate or a packet of chips or both. Chocolate worth 10 cents and a packet of chips worth 20 cents. A customer
can enter one coin at a time. Finally the requested product is dispensed and the total cost appears at the display
panel. Machine again goes to the idle state.

3. Create an interface Order which is acting as a command. Also create a Stock class which acts as a request. Then
create concrete command classes BuyStock and SellStock implementing Order interface which will do actual
command processing. A class Broker must be created which acts as an invoker object. It can take and place
orders. Broker object uses command pattern to identify which object will execute which command based on the
type of command. CommandPatternDemo, a demo class, will use Broker class to demonstrate command pattern.
Attach printouts.

29
Software Design and Testing Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Printouts:

30
Software Design and Testing Rubric Sheet for Grading
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

DEPARTMENT OF COMPUTER & INFORMATION SYSTEMS ENGINEERING


BACHELORS IN COMPUTER SYSTEMS ENGINEERING
RUBRIC

Course Code and Title: CS-325 Software Development and Testing

Week #: _______________

Lab #: _______________

Assigned problem: _______________________________________________________________________________

______________________________________________________________________________________________

______________________________________________________________________________________________
CRITERIA AND SCALES
Criterion 1: To what level has the student understood the problem?
0-2 3-7 8 – 10
The student has no idea of the The student has incomplete idea of The student has complete idea of the
problem. the problem. problem.
Criterion 2: To what extent has the student implemented the solution?
0-2 3-7 8 – 10
The solution is syntactically and
The solution has not been The solution is syntactically correct
logically correct for the stated
implemented. but has logical errors.
problem parameters.
Criterion 3: How efficient is the proposed solution?
0-2 3-7 8 – 10
The solution is computationally
The solution does not address the The solution exhibits redundancy
efficient and covers all aspects of the
problem adequately. and partially covers the problem.
problem.
Criterion 4: How did the student answer questions relevant to the task?
0-2 3-7 8 - 10
The student answered few questions The student answered most of the The student answered all the
relevant to the solution. questions relevant to the solution. questions relevant to the solution.

Total Marks: ________________________

Teacher’s Signature: ___________________

31

You might also like