Lecture Notes 1 - Software Design Patterns-1
Lecture Notes 1 - Software Design Patterns-1
MVC Pattern
MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to
separate application's concerns.
Model - Model represents an object or JAVA POJO carrying data. It can also
have logic to update controller if its data changes.
View - View represents the visualization of the data that model contains.
Controller - Controller acts on both model and view. It controls the data flow into
model object and updates the view whenever data changes. It keeps view and
model separate.
Implementation
We are going to create a Student object acting as a model.StudentView will be a view
class which can print student details on console and StudentController is the controller
class responsible to store data in Student object and update
view StudentView accordingly.
MVCPatternDemo, our demo class, will use StudentController to demonstrate use of
MVC pattern.
Step 1
Create Model.
Student.java
public class Student {
private String rollNo;
private String name;
Step 2
Create View.
StudentView.java
public class StudentView {
public void printStudentDetails(String studentName, String
studentRollNo){
System.out.println("Student: ");
System.out.println("Name: " + studentName);
System.out.println("Roll No: " + studentRollNo);
}
}
Step 3
Create Controller.
StudentController.java
public class StudentController {
private Student model;
private StudentView view;
Step 4
Use the StudentController methods to demonstrate MVC design pattern usage.
MVCPatternDemo.java
public class MVCPatternDemo {
public static void main(String[] args) {
controller.updateView();
controller.updateView();
}
Step 5
Verify the output.
Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10
Observer Pattern
Observer pattern is used when there is one-to-many relationship between objects such
as if one object is modified, its dependent objects are to be notified automatically.
Observer pattern falls under behavioral pattern category.
Implementation
Observer pattern uses three actor classes. Subject, Observer and Client. Subject is an
object having methods to attach and detach observers to a client object. We have
created an abstract class Observer and a concrete class Subject that is extending
class Observer.
ObserverPatternDemo, our demo class, will use Subject and concrete class object to
show observer pattern in action.
Step 1
Create Subject class.
Subject.java
import java.util.ArrayList;
import java.util.List;
Step 2
Create Observer class.
Observer.java
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
Step 3
Create concrete observer classes
BinaryObserver.java
public class BinaryObserver extends Observer{
public BinaryObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( "Binary String: " +
Integer.toBinaryString( subject.getState() ) );
}
}
OctalObserver.java
public class OctalObserver extends Observer{
@Override
public void update() {
System.out.println( "Octal String: " +
Integer.toOctalString( subject.getState() ) );
}
}
HexaObserver.java
public class HexaObserver extends Observer{
@Override
public void update() {
System.out.println( "Hex String: " +
Integer.toHexString( subject.getState() ).toUpperCase() );
}
}
Step 4
Use Subject and concrete observer objects.
ObserverPatternDemo.java
public class ObserverPatternDemo {
public static void main(String[] args) {
Subject subject = new Subject();
new HexaObserver(subject);
new OctalObserver(subject);
new BinaryObserver(subject);
Step 5
Verify the output.
First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010
o When a class wants that its sub-classes specify the objects to be created.
o When the parent classes choose the creation of objects to its sub-classes.
Calculate Electricity Bill : A Real World Example of Factory
Method
Step 1: Create a Plan abstract class
import java.io.*;
abstract class Plan{
protected double rate;
abstract void getRate();
public void calculateBill(int units){
System.out.println(units*rate);
}
}//end of Plan class.
Step 2: Create the concrete classes that extends Plan abstract class.
class DomesticPlan extends Plan{
//@override
public void getRate(){
rate=3.50;
}
}//end of DomesticPlan class.
class CommercialPlan extends Plan{
//@override
public void getRate(){
rate=7.50;
}
/end of CommercialPlan class.
class InstitutionalPlan extends Plan{
//@override
public void getRate(){
rate=5.50;
}
/end of InstitutionalPlan class.
class GetPlanFactory{
//use getPlan method to get object of type Plan
public Plan getPlan(String planType){
if(planType == null){
return null;
}
if(planType.equalsIgnoreCase("DOMESTICPLAN")) {
return new DomesticPlan();
}
else if(planType.equalsIgnoreCase("COMMERCIALPLAN")){
return new CommercialPlan();
}
else if(planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {
return new InstitutionalPlan();
}
return null;
}
}//end of GetPlanFactory class.
Step 4: Generate Bill by using the GetPlanFactory to get the object of concrete classes
by passing an information such as type of plan DOMESTICPLAN or COMMERCIALPLAN or
INSTITUTIONALPLAN.
import java.io.*;
class GenerateBill{
public static void main(String args[])throws IOException{
GetPlanFactory planFactory = new GetPlanFactory();
System.out.print("Enter the name of plan for which the bill will be generated: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String planName=br.readLine();
System.out.print("Enter the number of units for bill will be calculated: ");
int units=Integer.parseInt(br.readLine());
Plan p = planFactory.getPlan(planName);
//call getRate() method and calculateBill()method of DomesticPaln.
System.out.print("Bill amount for "+planName+" of "+units+" units is: ");
p.getRate();
p.calculateBill(units);
}
}//end of GenerateBill class.
Output
References:
https://www.tutorialspoint.com/design_pattern/mvc_pattern.htm
https://www.tutorialspoint.com/design_pattern/observer_pattern.htm
https://www.javatpoint.com/factory-method-design-pattern#:~:text=A%20Factory%20Pattern%20or
%20Factory,the%20instance%20of%20the%20class.