Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

History ? Design patterns gained popularity in computer science in 1994 ? Book “

ID: 3774959 • Letter: H

Question

History

? Design patterns gained popularity in computer science in 1994

? Book “Design Patterns: Elements of Reusable Object-Oriented Software” was

published by

? Erich Gamma

? Richard Helm

? Ralph Johnson

? John Vlissides

? They are referred to as “Gang of Four” (GoF)

Design Patterns

? Reusable solutions to common problems

? Think of reusable templates

? Can be implemented in most languages

? Design patterns are not just for Java

? Patterns can help show relationships between classes without having the entire application built

Design Patterns

? Done correctly, helps speed up the development process

? Using proven design patterns, one can help reduce some of the “unknowns”

which can cause major problems

? Improves readability

? Programmers who are familiar with design patterns can easily read and understand the code

Design Patterns

? 4 different classifications

? Creational pattern

? Structural pattern

? Behavioral pattern

? Concurrency pattern (too advanced for COMP 110)

Creational Patterns

? Deal with object creation

? Abstract factory

? Builder

? Factory method

? Lazy initialization

? Multiton

? Object pool

? Prototype

? Resource acquisition is initialization

? Singleton

Singleton Pattern

? Restricts the instantiation of a class to one object

? Using one object to perform a series of actions in a software system

? Use when appropriate

Singleton Pattern

? How to implement a singleton pattern?

? Using an instance variable

? Using a getInstance() method

? private constructor

Singleton Pattern - Example

class SomeClass {
private static SomeClass instance = new SomeClass(); private SomeClass() { // blank }
public static SomeClass getInstance() {...}
public void set(int x) {...}
public int get() {...}

}

Singleton Pattern - Example

...
public SomeClass getInstance() {

      return instance;

   }

...

Singleton Pattern - Example

Your driver should be similar to this:

//Singleton s = new Singleton(); // error Singleton sObj1;
//sObj1.doStuff(); // error
sObj1 = Singleton.getInstance(); sObj1.set(7); // ok

      Singleton sObj2 = Singleton.getInstance();

      sObj2.set(77); // ok

Structural Pattern
? Relationship between entities

? Adapter (a.k.a Wrapper)

? Bridge

? Composite

? Decorator

? Extension object

? Facade

? Flyweight

? Front controller

? Marker

? Module

? Proxy

? Twin

Adapter Pattern

? Allows the interface of an existing class to be used by another interface

? Helps existing classes work with other classes without modifying their code

(code of the existing class)

Adapter Pattern - Example

? Interface #1

? Interface #2

? Concrete classes implements interface #1

? Concrete classes implements interface #2

? Adapter class implements interface #1

? Concrete class implements interface #1

? Driver which uses the Concrete class that implemented interface #1

RemoteControl.java

public interface RemoteControl {

   public void power(String model, String action);

}

UniversalRemoteControl.java

public interface UniversalRemoteControl {

   public void powerSamsung(String action);

   public void powerSony(String action);

}

Samsung.java

public class Samsung implements UniversalRemoteControl {

   public void powerSamsung(String action) {

      if(action.equals(“on”)) {

         System.out.println(“Turning on Samsung device...”);

      }

      // and more conditions...

   } // end powerSamsung

   public void powerSony(String action) {

      // empty

   }

} // end Samsung

Sony.java

public class Sony implements UniversalRemoteControl {

   public void powerSamsung(String action) {

      // empty

}

   public void powerSony(String action) {

      if(action.equals(“on”)) {

         System.out.println(“Turning on Sony device...”);

      } // end if

      // and more conditions...

   } // end powerSony

} // end Sony

RemoteAdapter.java

public class RemoteAdapter implements RemoteControl {

   UniversalRemoteControl urc;

public RemoteAdapter(String model) { if(model.equalsIgnoreCase("samsung") ){

         urc = new Samsung();

      } else if (model.equalsIgnoreCase("sony")){

         urc = new Sony();

      }

} ...

RemoteAdapter.java

   public void power(String model, String action) {

      if(model.equalsIgnoreCase("samsung")) {

         urc.powerSamsung(action);

      }

      else if(model.equalsIgnoreCase("sony")) {

         urc.powerSony(action);

      }

   } // end power

} // end class RemoteAdapter

Remote.java

public class Remote implements RemoteControl { RemoteAdapter remoteAdapter;
public void power(String model, String action) {

if(model.equalsIgnoreCase("samsung") || model.equalsIgnoreCase("sony")) { remoteAdapter = new RemoteAdapter(model);
remoteAdapter.power(model, action);

}
else {

         System.out.println(model + " not supported.");

      }

} }

RemoteDemo.java

class RemoteDemo {

   public static void main(String[] args) {

      Remote logitech = new Remote();

      logitech.power("samsung", "on");

      logitech.power("sony"   , "on");

      logitech.power("vizio" , "on");

} }

Behavioral Pattern
? Deal with communications between objects

? Blackboard

? Chain of responsibility

? Command

? Interpreter

? Iterator

? Mediator

? Memento

? Null object

? Observer or Publish/subscribe

? Servant

? Specification

? State

? Strategy

? Template method

? Visitor

State Pattern

? Some (or all) member variables are static

? Multiple instances will see the same data

State.java

class State {

   private static int numOfInstances = 0;

   private int myVal;

   public State(int myVal) {

      this.myVal = myVal;

      numOfInstances++;

}

   public int getNumOfInstances() {

      return numOfInstances;

}

   public int getVal() {

      return myVal;

} }

StateDriver.java

class StateDriver {

   public static void main(String[] args) {

      State s1, s2, s3;

      s1 = new State(100);

      s2 = new State(200);

      s3 = new State(300);

      System.out.println(s1.getNumOfInstances());

      System.out.println(s2.getNumOfInstances());

      System.out.println(s3.getNumOfInstances());

      System.out.println(s1.getVal());

      System.out.println(s2.getVal());

      System.out.println(s3.getVal());

} }

Concurrency Pattern

? Deal with multithreaded programming paradigm

? Active Object

? Balking

? Binding properties

? Block chain

? Double-checked locking

? Event-based asynchronous

? Guarded suspension

? Join

? Lock

? Messaging design pattern (MDP)

? Monitor object

? Reactor

? Read-write lock

? Scheduler

? Thread pool

? Thread-specific storage

Lab Singleton.java Driver) Monostate java Driver) Adapter java (including Driver, 7 files)

Explanation / Answer

Singleton Example:

Student.java

package designpatterns;

//Singleton class called Student that maintains all information for a student

public class Student {

  

   //member variables for the class

   int StudentID;

   private static Student student = new Student();

  

   private Student()

   {

       //leaving this blank

   }

   public int getStudentID() {

       return StudentID;

   }

   public void setStudentID(int studentID) {

       StudentID = studentID;

   }

  

   public static Student getInstance()

   {

       return student;

   }

}

StudentDriver.java

package designpatterns;

public class StudentDriver {

   public static void main(String[] args) {

       //declaring an object for the class

       Student std;

       //calling the static getInstance() method

       std = Student.getInstance();

       //setting a value for the member variable

       std.setStudentID(2001);

      

       //one more object

       Student std1 = Student.getInstance();

       std1.setStudentID(2002);

   }

}

MonoState Example

Product.java

package designpatterns;

//Product class to explain MonoState pattern

public class Product {

  

   private static int NumOfProducts = 0;

   private int productID;

  

   //constructor for the class

   public Product(int productID)

   {

       this.productID = productID;

       NumOfProducts++;

   }

   //get method

   public int getProductID() {

       return productID;

   }

   //set method

   public void setProductID(int productID) {

       this.productID = productID;

   }

  

   public int getNumberOfProducts()

   {

       return NumOfProducts;

   }

}

ProductDriver.java

package designpatterns;

public class ProductDriver {

   public static void main(String[] args) {

       //declaring the products

       Product prod1, prod2, prod3;

      

       //initializing with product id

       prod1 = new Product(5001);

       prod2 = new Product(5002);

       prod3 = new Product(5003);

      

       //Printing the values

       //Number of products

       //this is a static value and hence remains the same for different objects

       // so the total products are three - prod1, prod2, prod3

       System.out.println(prod1.getNumberOfProducts());

       System.out.println(prod2.getNumberOfProducts());

       System.out.println(prod3.getNumberOfProducts());

      

       //product ids

       System.out.println(prod1.getProductID());

       System.out.println(prod2.getProductID());

       System.out.println(prod3.getProductID());

   }

}

OUTPUT:

3

3

3

5001

5002

5003

Adapter Example

Bank.java

package designpatterns;

//This is a common interface - bank to represent all the banks

public interface Bank {

  

   public void deposit(String bankName, double amount);

}

GlobalBank.java

package designpatterns;

//these are the banks that the application will support

public interface GlobalBank {

  

   public void depositAtICICI(double amount);

   public void depositAtStandardChartered(double amount);

}

ICICIBank.java

package designpatterns;

//this is one of the banks supported

public class ICICIBank implements GlobalBank{

   @Override

   public void depositAtICICI(double amount) {

      

       System.out.println("Depositing $" + amount + " at ICICI bank");

   }

   @Override

   public void depositAtStandardChartered(double amount) {

       //this will remain empty since this class is only for ICICI Bank

      

   }

  

}

StandardChartered.java

package designpatterns;

//this is one of the banks supported

public class StandardChartered implements GlobalBank{

   @Override

   public void depositAtICICI(double amount) {

       //this will remain blank

      

   }

   @Override

   public void depositAtStandardChartered(double amount) {

       System.out.println("Depositing $" + amount + " at Standard Chartered bank");

      

   }

}

BankAdapter.java

package designpatterns;

//adapter for all the supported banks

public class BankAdapter implements Bank{

   GlobalBank bank;

  

   public BankAdapter(String bankName) {

       if(bankName.equals("ICICI"))

           bank = new ICICIBank();

       else if(bankName.equals("Standard Chartered"))

           bank = new StandardChartered();

   }

   @Override

   public void deposit(String bankName, double amount) {

       if(bankName.equals("ICICI"))

           bank.depositAtICICI(amount);

       else if(bankName.equals("Standard Chartered"))

           bank.depositAtStandardChartered(amount);

      

   }

}

Banker.java

package designpatterns;

//the class that will handle any bank without throwing error or halting the application

public class Banker implements Bank{

   BankAdapter adapter;

  

   @Override

   public void deposit(String bankName, double amount) {

       if(bankName.equals("ICICI") || bankName.equals("Standard Chartered"))

       {

           adapter = new BankAdapter(bankName);

           adapter.deposit(bankName, amount);

       }

       else

           System.out.println("No such Bank found: " + bankName);

      

   }

}

BankerDriver.java

package designpatterns;

//driver program

public class BankerDriver {

   public static void main(String[] args) {

       Banker banker = new Banker();

       banker.deposit("ICICI", 2000);

       banker.deposit("Standard Chartered", 3000);

       banker.deposit("World Bank", 10000);

   }

}

OUTPUT:

Depositing $2000.0 at ICICI bank

Depositing $3000.0 at Standard Chartered bank

No such Bank found: World Bank

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote