You are on page 1of 13

Software Modelling Design

Case studies Assignment on Unit V

Name:- Anjali Singh ( TEA )

Roll No. :- 17145

Case 1

Suppose we are building a cricket app that notifies viewers about the information such as current score,
run rate etc. Suppose we have made two display elements CurrentScoreDisplay and
AverageScoreDisplay. CricketData has all the data (runs, bowls etc.) and whenever data changes the
display elements are notified with new data and they display the latest data accordingly. Write its
implementation by using a suitable design pattern.

Design Pattern :- Observer Pattern


IMPLEMENTATION

import java.util.ArrayList; {
import java.util.Iterator;
interface Subject for (Iterator<Observer> it =
{ observerList.iterator();
it.hasNext();)
public void registerObserver(Observer o);
public void unregisterObserver(Observer {
o); public void notifyObservers();
}
class CricketData implements Subject
{
int runs;
int wickets;

float overs;

ArrayList<Observer> observerList;
public CricketData() {

observerList = new ArrayList<Observer>();


}
@Override

public void registerObserver(Observer o)


{ observerList.add(o);

}
@Override

public void unregisterObserver(Observer o)


{ observerList.remove(observerList.indexOf(o));

}
@Override
public void notifyObservers()

1
runs = getLatestRuns();
} wickets = getLatestWickets();
private int getLatestRuns() overs = getLatestOvers();
{ notifyObservers();
return 90; }
} }
private int getLatestWickets() interface Observer
{ {
return 2;
} public void update(int runs, int wickets,
private float getLatestOvers() float overs);
{
return (float)10.2; }

} class AverageScoreDisplay implements Observer


public void dataChanged() {
{ private float runRate;
private int predictedScore;

2
Observer o = it.next(); public void update(int runs, int wickets,
o.update(runs,wickets,overs); float overs)
} {
1

System.out.println("\nCurrent Score Display:\n"


this.runRate =(float)runs/overs; + "Runs: " + runs +
this.predictedScore = (int)(this.runRate * "\nWickets:" + wickets +
50); display(); "\nOvers: " + overs );
}
}
public void display() }
class Main
{
{
System.out.println("\nAverage Score Display: \n" public static void main(String args[])
+ "Run Rate: " + runRate + {
"\nPredictedScore: " +
AverageScoreDisplay averageScoreDisplay =
predictedScore); new AverageScoreDisplay();
} CurrentScoreDisplay currentScoreDisplay = new
} CurrentScoreDisplay();
class CurrentScoreDisplay implements Observer CricketData cricketData = new CricketData();
{
private int runs, wickets; cricketData.registerObserver(averageScoreDisplay);
private float overs;
cricketData.registerObserver(currentScoreDisplay);
public void update(int runs, int cricketData.dataChanged();
wickets, float overs)
cricketData.unregisterObserver(averageScoreDisplay );
{
this.runs = runs; cricketData.dataChanged();
this.wickets = wickets; }
this.overs = overs; }
display();
}
public void display()
{

OUTPUT

Average Score Display:

Run Rate: 8.823529

PredictedScore: 441

3
Current Score Display:

Runs: 90

Wickets:2

Overs: 10.2

Current Score Display:

Runs: 90

Wickets:2

Overs: 10.2

4
Case 2

Suppose a developer wants to create a simple DBConnection class to connect to a


database and wants to access the database at multiple locations from code. Write its
implementation by using a suitable design pattern.

Design Pattern :- Singleton Pattern

IMPLEMENTATION
public class Connect_db

static Connection con=null;


public static Connection getConnection()
{
if (con != null) return con;
return getConnection(db, user, pass);
}
private static Connection getConnection(String db_name,String user_name,String
password)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/"+db_name+"?
user="+user_name+"&password="+password):
}
catch(Exception e)
{
e.printStackTrace();
}
return con;
}
}

Case 3

5
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. Birds have some similar functionality but
implement a different interface. Write its implementation by using a suitable design
pattern.

Design Pattern :- Adapter Pattern

IMPLEMENTATION

interface Bird
{
public void fly();
public void makeSound();
}
class Sparrow implements Bird
{
public void fly()
{
System.out.println("Flying");
}
public void makeSound()
{
System.out.println("Chirp Chirp");
}
}

interface ToyDuck
{
public void squeak();
}
class PlasticToyDuck implements ToyDuck
{
public void squeak()
{
System.out.println("Squeak");
}
}
class BirdAdapter implements ToyDuck
{
Bird bird;

public BirdAdapter(Bird bird)


{
this.bird = bird;
}
public void squeak()
{
bird.makeSound();
}

}
class Main

6
{
public static void main(String args[])

{
Sparrow sparrow = new Sparrow();
ToyDuck toyDuck = new PlasticToyDuck();
ToyDuck birdAdapter = new BirdAdapter(sparrow);
System.out.println("Sparrow...");
sparrow.fly();
sparrow.makeSound();

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

OUTPUT

Sparrow...

Flying

Chirp Chirp

ToyDuck...

Squeak

BirdAdapter...

Chirp Chirp

7
3

8
Case 4

Consider the scenario of college internet. Students should have access to the limited sites.
Social networking sites are not allowed to access. Write its implementation by using
suitable design pattern.

Design Pattern :- Proxy Pattern


IMPLEMENTATION

Interface of Internet

package com.anju.demo.proxy;

public interface Internet

{
public void connectTo(String serverhost) throws Exception;
}

RealInternet.java

package com.anju.demo.proxy;

public class RealInternet implements Internet


{

@Override
public void connectTo(String serverhost)
{

System.out.println("Connecting to "+ serverhost);


}
}

ProxyInternet.java

package com.anju.demo.proxy;

import java.util.ArrayList;

import java.util.List;

public class ProxyInternet implements Internet


{

private Internet internet = new RealInternet();


private static List<String> bannedSites;

static
{
bannedSites = new ArrayList<String>();
bannedSites.add("Instagram.com");
bannedSites.add("Google+.com");

bannedSites.add("MayureshD6.com");
bannedSites.add("lnm.com");
}
@Override

9
public void connectTo(String serverhost) throws Exception
{
if(bannedSites.contains(serverhost.toLowerCase()))
{
throw new Exception("Access Denied");
}

internet.connectTo(serverhost);
}

Client.java

package com.anju.demo.proxy;

public class Client

{
public static void main (String[] args)

{
Internet internet = new ProxyInternet();
try

{
internet.connectTo("Facebook.org");
internet.connectTo("abc.com");
}
catch (Exception e)

{
System.out.println(e.getMessage());
}
}
}

OUTPUT

Connecting to Facebook.org

Access Denied

10
Case 5
Suppose we are building an application that requires us to maintain a list of notifications. we
are creating a notification bar in our application that displays all the notifications which are held
in a notification collection. Write its implementation by using suitable design pattern.

Design Pattern :- Iterator Pattern .


IMPLEMENTATION
class Notif

String notification;

public Notif(String notification)


{
this.notification = notification;
}
public String getNotification()

{
return notification;
}
}

interface Collection
{
public Iterator createIterator();

class NotifCollec implements Collection

{
static final int MAX_ITEMS = 6;
int numberOfItems = 0;

Notif[] notificationList;

public NotifCollec()

{
notificationList = new Notif[MAX_ITEMS];

addItem("Notif 1");
addItem("Notif 2");
addItem("Notif 3");
}

public void addItem(String str)


{
Notif notification = new Notif(str);
if (numberOfItems >= MAX_ITEMS)
System.err.println("Full");
else
{

notificationList[numberOfItems] = notification;
numberOfItems = numberOfItems + 1;
}
}

public Iterator createIterator()

11
{
return new NotificationIterator(notificationList);
}
}

interface Iterator
{

boolean hasNext();
Object next();
}
class NotificationIterator implements Iterator
{
Notif[] notificationList;

int pos = 0;

public NotificationIterator (Notif[] notificationList)

{
this.notificationList = notificationList;
}

public Object next()


{

Notif notification = notificationList[pos];


pos += 1;
return notification;

public boolean hasNext()

{
if (pos >= notificationList.length ||
notificationList[pos] == null)
return false;
else

return true;
}
}

class NotifBAR
{
NotifCollec notifications;

public NotifBAR(NotifCollec notifications)

{
this.notifications = notifications;
}

public void PrintNotif()


{

Iterator iterator = notifications.createIterator();


System.out.println("-------NOTIFICATION BAR------------");
while (iterator.hasNext())
{
Notif n = (Notif)iterator.next();

System.out.println(n.getNotification());
}
}
}

12
class Main
{
public static void main(String args[])
{
NotifCollec nc = new NotifCollec();
NotifBAR nb = new NotifBAR(nc);
nb.PrintNotif();
}

OUTPUT

-------NOTIFICATION BAR------------

Notification 1

Notification 2

Notification 3

13

You might also like