Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
139 views

Lecture Notes 1 - Software Design Patterns-1

The document discusses three software design patterns: 1. MVC Pattern - This pattern separates an application into three main components: the model, the view, and the controller. A sample implementation using a Student model, StudentView, and StudentController is provided. 2. Observer Pattern - This pattern is used for one-to-many dependency between objects. It involves a Subject, Observer, and Client. Concrete observer classes like BinaryObserver are created to observe a Subject. 3. Factory Method Pattern - This pattern provides an interface for creating objects but leaves the object creation to subclasses. It is used when the class doesn't know the subclasses needed to create or wants subclasses to specify object creation. A sample electricity

Uploaded by

Nyerhovwo Ozah
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views

Lecture Notes 1 - Software Design Patterns-1

The document discusses three software design patterns: 1. MVC Pattern - This pattern separates an application into three main components: the model, the view, and the controller. A sample implementation using a Student model, StudentView, and StudentController is provided. 2. Observer Pattern - This pattern is used for one-to-many dependency between objects. It involves a Subject, Observer, and Client. Concrete observer classes like BinaryObserver are created to observe a Subject. 3. Factory Method Pattern - This pattern provides an interface for creating objects but leaves the object creation to subclasses. It is used when the class doesn't know the subclasses needed to create or wants subclasses to specify object creation. A sample electricity

Uploaded by

Nyerhovwo Ozah
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Software Design Patterns

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;

public String getRollNo() {


return rollNo;
}

public void setRollNo(String rollNo) {


this.rollNo = rollNo;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = 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;

public StudentController(Student model, StudentView view){


this.model = model;
this.view = view;
}

public void setStudentName(String name){


model.setName(name);
}

public String getStudentName(){


return model.getName();
}

public void setStudentRollNo(String rollNo){


model.setRollNo(rollNo);
}

public String getStudentRollNo(){


return model.getRollNo();
}
public void updateView(){
view.printStudentDetails(model.getName(), model.getRollNo());
}
}

Step 4
Use the StudentController methods to demonstrate MVC design pattern usage.
MVCPatternDemo.java
public class MVCPatternDemo {
public static void main(String[] args) {

//fetch student record based on his roll no from the database


Student model = retriveStudentFromDatabase();

//Create a view : to write student details on console


StudentView view = new StudentView();

StudentController controller = new StudentController(model,


view);

controller.updateView();

//update model data


controller.setStudentName("John");

controller.updateView();
}

private static Student retriveStudentFromDatabase(){


Student student = new Student();
student.setName("Robert");
student.setRollNo("10");
return student;
}
}

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;

public class Subject {

private List<Observer> observers = new ArrayList<Observer>();


private int state;

public int getState() {


return state;
}

public void setState(int state) {


this.state = state;
notifyAllObservers();
}

public void attach(Observer observer){


observers.add(observer);
}

public void notifyAllObservers(){


for (Observer observer : observers) {
observer.update();
}
}
}

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{

public OctalObserver(Subject subject){


this.subject = subject;
this.subject.attach(this);
}

@Override
public void update() {
System.out.println( "Octal String: " +
Integer.toOctalString( subject.getState() ) );
}
}

HexaObserver.java
public class HexaObserver extends Observer{

public HexaObserver(Subject subject){


this.subject = subject;
this.subject.attach(this);
}

@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);

System.out.println("First state change: 15");


subject.setState(15);
System.out.println("Second state change: 10");
subject.setState(10);
}
}

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

Factory Method Pattern


A Factory Pattern or Factory Method Pattern says that just define an interface or
abstract class for creating an object but let the subclasses decide which class
to instantiate. In other words, subclasses are responsible to create the instance of the
class.

The Factory Method Pattern is also known as Virtual Constructor.

Advantage of Factory Design Pattern


o Factory Method Pattern allows the sub-classes to choose the type of objects to
create.

o It promotes the loose-coupling by eliminating the need to bind application-


specific classes into the code. That means the code interacts solely with the
resultant interface or abstract class, so that it will work with any classes that
implement that interface or that extends that abstract class.

Usage of Factory Design Pattern


o When a class doesn't know what sub-classes will be required to create

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.

UML for Factory Method Pattern


o We are going to create a Plan abstract class and concrete classes that extends
the Plan abstract class. A factory class GetPlanFactory is defined as a next step.
o GenerateBill class will use GetPlanFactory to get a Plan object. It will pass
information (DOMESTICPLAN / COMMERCIALPLAN / INSTITUTIONALPLAN) to
GetPalnFactory to get the type of object it needs.

 
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.  

Step 3: Create a GetPlanFactory to generate object of concrete classes based on given


information..

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.  

download this Electricity bill Example

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.

You might also like