MITS4002 Object-Oriented Design Patterns in Java - A Research Study

Verified

Added on  2023/06/04

|15
|2645
|493
Report
AI Summary
This report provides an overview of object-oriented design patterns in Java, focusing on creational and strategy patterns. It discusses creational patterns like abstract factory, singleton, builder, factory method, and prototyping, highlighting their advantages and disadvantages. The report then delves into the strategy design pattern, demonstrating its implementation in the context of a shopping cart's computePrice and checkOut methods, complete with Java code examples. Security implementation using the strategy pattern with different payment methods like Visa and MasterCard is also illustrated. The document also references research study MITS4002 Object-Oriented Software Development.
Document Page
Running head: OBJECT ORIENTED DESIGN PATTERNS IN JAVA
Object Oriented Design Patterns in Java
Name
Institution
Date
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
OBJECT ORIENTED DESIGN PATTERNS 2
Question 1
Creational Design Patterns
As outlined by Smith (2015), creational patterns are meant to abstract the operation
behind creation of class objects. Similarly, he emphasizes that they are used to engage a user in a
disguise regarding objects creation, composition and their representation. Creation pattern are
known to encapsulate cognition around choosing concrete classes implemented referred to the
approach of objects creation through interfaces. The pattern allows for flexibleness performing
activities ranging from creation of different object types, an engaging responsibility to create as
well as determining how and when to create the objects. As such, creational patterns have been
divided into five major types including abstract factory, singleton, builder, factory method and
prototyping (Gamma 1999). The pattern can well be attributed to creating a maze game which
involves objectives including finding an exit from the maze, solving troubles as well as creating
maps.
Abstract factory is credited to various advantages such as isolating concrete objects.
Secondly, it provides easy exchange in intersection of families, with a concrete factory being
created only once in a singleton as well as alteration of a family of products, hence, the instance
of factory. Lastly it encourages products to consistency. Nevertheless, abstract factory poses
various cons including trouble to support fresh types of products such as widgets, thus requires
extension of interface. Secondly, apart from being a singleton it doesn’t allow clients to know the
type of produced intersection, hence, need for multicasting (Smith 2015). Creation of concrete
products are commonly done using factory methods if not by prototyping. Factories can be
extended through parameterized creation of a product. The latter is used to specify a type of
Document Page
OBJECT ORIENTED DESIGN PATTERNS 3
object intended for creation in class identifiers, data type as well as other features that can
discover products.
A motivation behind it includes a system for software able to maintain numerous files to
a client. For instance, essential abstraction constitutes of a document and applications structure.
There are five participants of factory method namely product which defines an interface
regarding the objectives intended for creation. A concrete product can be used to implement the
product interface. Thirdly, a creator holds the factory method hence returning a product.
Similarly, it may determine default execution, hence, returns a default concrete product object. A
distinction between the factory method and abstract factory is that, whereas the latter conforms
to a double value in abstraction, the former’s use of interfaces otherwise or an abstract class
doesn’t recognize the specific concrete class to be returned. Therefore, the factory method has
been attributed to pros including having a user code that is freed from classes for particular
software. Additionally, it offers a fleece to continue sub classing. Nevertheless, a con draw to it
claims that users are mandated to create a subclass to merely create concrete product objects.
Singletons ascertains that a created class only contains a single instance which is can be
globally accessed. Therefore, developers are required to use Singleton strictly for class that can
only have one instance so as to fend off need for passing parameters of the object. It participates
being static thus, defines operations which allow users to access distinct instance and is
responsible for making the instance.
Document Page
OBJECT ORIENTED DESIGN PATTERNS 4
Question 2
Design Problem 1
ComputePrice Method
Using Strategy Design Pattern to Implement Compute Price
As depicted by the class codes below on how to implement a ShoppingCart, it uses the
Strategy Pattern simple techniques where one object instructs another to perform the task.
public class ItemCart
{
public ItemCart(String theCode) {
Code = theCode; // assume "1234" -> Bacon
}
public ItemCart(SaveItem theItem) {
MappingItemStore(theItem);
}
// declaring the props: Code, Name, Quantity, Cost
public void Preparation() {
if(theQuantity > 0) {
// Alert and return when operation is invalid
// The one time call in each item
}
// Sample. Calling back from the database.
var theItem = new SaveItem { Code = theCode, Name =
"Bacon", Cost = 2.49, Tax = 0 /* etc */ }
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
OBJECT ORIENTED DESIGN PATTERNS 5
MappingItemStore(theItem);
Quantity = 1;
}
public void UpdatingTheQuantity(int theQuantity) {
Quantity = theQuantity;
Cost = Cost * Quantity;
}
private void MappingItemStore(SaveItem theItem) {
Code = theItem.Code;
Name = theItem.Name;
Cost = CalculatingCost(theItem.Cost, theItem.Tax);
}
private static double ComputePrice(double theCost, double
theTax) {
// If tax > 0, apply it to cost
// if (theCost + theTax > 26) && (theCost + theTax < 50)){
Return iChipKart = T-Shirt;
} else if (theCost + theTax > 26 && (theCost + theTax < 50)){
Return iChipKark = Backpack;
} else if (theCost + theTax > 100){
Return iChipKark = portableDisk;
// else return cost as is
}
}
}
Document Page
OBJECT ORIENTED DESIGN PATTERNS 6
Second Implementation of Strategy Pattern for computePrice in Shopping Cart.
public class SCart {
List<String> theItems;
double allTotal;
public SCart(){
theItems = new ArrayList<String>();
}
public void appendItems(String theItem){
theItems.append(theItem);
}
public void removeItems(String theItem){
theItems.remove(theItem);
}
public void getNumberOfItems(){
System.out.println(theItems.size());
}
public String getItemName(int theIndex){
return theItems.get(theIndex);
}
public void computePrice(){
total = 0;
for(String var1: theItems){
if (var1.equals("")){
total += 3.0;
}else if (var1.equals("")){
total += 5.0;
}else if (var1.equals("")){
total += 2.50;
}
}
Document Page
OBJECT ORIENTED DESIGN PATTERNS 7
System.out.println(allTotal);
}
}
Third Implementation of Strategy Pattern for computePrice in Shopping Cart.
public class SCart {
protected Dictionary<Product, int> theItems;
// throwing a list of products List<Product>
public void AppendItem( Product freshItem ) {
if ( ! theItems.Contains(freshItem) ) // SRP in action
theItems.Append(freshItem);
theItems[freshItem].count++;
}
public decimal totalOfCart() {
foreach ( thing in theItems ) {
allTotal += theItems[thing].GetPrice * theItems[thing].count;
}
}
// code in "cart"/"shopping" terminology. aka Domain Specific
Language - DSL.
public string Receipt() { return this.ToString(); }
public override string ToString() {
string indivd = "";
foreach ( thing in theItems ) {
indivd += theItems[thing].ToString() + "\n"; // SRP in
action
}
indivd += "\n\n Total: " + totalOfCart();
return indivd;
}
}
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
OBJECT ORIENTED DESIGN PATTERNS 8
public class SCart {
private final List<Item> theItems;
public SCart() {
theItems = new ArrayList<Item>();
}
public void appendItem(Item theItem) {
theItems.append(theItem);
}
public double computeCost() {
double allTotal = 0.0;
for (Item theItem : theItems) {
total += theItem.getPrice();
}
return allTotal;
}
public boolean payUp(MethodOfPay theMethod) {
double totalCost = computeCost();
return theMethod.payUp(totalCost);
}
}
Design Problem 2
CheckOut
Using Strategy Design Pattern to Implement “checkOut” method in Shopping Cart
Code 1
import java.util.*;
public class Checkout {
private Set<CheckoutStrategy> strategies = new HashSet<>();
public static Map<String, Double> PRICE_MAP = new HashMap<>();
static {
Document Page
OBJECT ORIENTED DESIGN PATTERNS 9
PRICE_MAP.put("Shirt", 0.25);
PRICE_MAP.put("Backpack", 0.6);
}
public Checkout() {
this.strategies.add(new SummingStrategy());
}
public Checkout(CheckoutStrategy discountStrategy) {
this();
this.strategies.add(discountStrategy);
}
public double calculateTotal(List<String> strings) {
double[] result = new double[1];
for (CheckoutStrategy strategy : strategies) {
strategy.calculateTotal(strings, result);
}
return result[0];
}
}
Code 2
import java.util.List;
public interface CheckoutStrategy {
void calculateTotal(List<String> strings, double[] result);
}
Code 3
import java.util.List;
import static Checkout.PRICE_MAP;
public class SummingStrategy implements CheckoutStrategy {
@Override
Document Page
OBJECT ORIENTED DESIGN PATTERNS 10
public void calculateTotal(List<String> items, double[] result) {
result[0] = items.stream().mapToDouble(PRICE_MAP::get).sum();
}
}
Code 4
import Checkout;
import java.util.List;
public class DiscountStrategy implements CheckoutStrategy {
@Override
public void calculateTotal(List<String> items, double[] result) {
ItemCounter counter = items.stream().collect(ItemCounter::new,
ItemCounter::accept, ItemCounter::combine);
double appleDiscount = (counter.counts[ItemCounter.SHIRT_INDEX] /
2) * Checkout.PRICE_MAP.get("Shirt");
double orangeDiscount =(counter.counts[ItemCounter.BACKPACK_INDEX]
/ 3) * Checkout.PRICE_MAP.get("Orange");
result[0] -= shirtDiscount;
result[0] -= backpackDiscount;
}
Code 5
class ItemCounter {
static final int SHIRT_INDEX = 0;
static final int BACKPACK_INDEX = 1;
private int[] counts = new int[2];
public void accept(String item) {
switch (item) {
case "Shirt":
counts[SHIRT_INDEX]++;
break;
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
OBJECT ORIENTED DESIGN PATTERNS 11
case "Backpack":
counts[SHIRT_INDEX]++;
break;
}
}
public void combine(ItemCounter other) {
this.counts[SHIRT_INDEX] += other.getCounts()[SHIRT_INDEX];
this.counts[SHIRT_INDEX] += other.getCounts()[BACKPACK_INDEX];
}
public int[] getCounts() {
return counts;
}
}
}
Using Strategy Design Pattern to Implement Security in Shopping Cart
As shown by the pay method, the subroutine takes a single parameter related to checkout
method, hence, the alternative object as defined. As such, the process follows definition of the
MethodOfPay implemented as an interface. The reason for the latter was for the ability of the
strategy pattern to enable decision at the time of running the application. The concrete type
works towards making payment by passing it into the shopping cart as implemented earlier.
public interface MethodOfPay {
public boolean payUp(double theAmount);
}
The below object of payment is concrete as is implemented as Visa.
Document Page
OBJECT ORIENTED DESIGN PATTERNS 12
public class Visa implements MethodOfPay {
private final String title;
private final String noOfCard;
private final Date expiry;
public Visa(String title, String noOfCard, Date expiry) {
super();
this.title = title;
this.noOfCard = noOfCard;
this.expiry = expiry;
}
@Override
public boolean payUp(double theAmount) {
// Opening connection to Mastercard
// Verifying connection
// Paybill using these details
return true; // if payment goes through
}
}
The below security object of payment is concrete as is implemented as MasterCard.
public class TheMasterCard implements MethodOfPay {
private final String title;
private final String noOfCard;
private final Date expiry;
public TheMasterCard(String title, String noOfCard, Date expiry) {
super();
this.title = title;
this.noOfCard = noOfCard;
this.expiry = expiry;
}
@Override
public boolean payUp(double theAmount) {
// Opening connection to Mastercard
// Verifying connection
// Paybill using these details
return true; // if payment goes through
}
}
The below security object of payment is concrete as is implemented as Visa.
chevron_up_icon
1 out of 15
circle_padding
hide_on_mobile
zoom_out_icon
[object Object]