Get Instant Help From 5000+ Experts For
question

Writing: Get your essay and assignment written from scratch by PhD expert

Rewriting: Paraphrase or rewrite your friend's essay with similar meaning at reduced cost

Editing:Proofread your work by experts and improve grade at Lowest cost

And Improve Your Grades
myassignmenthelp.com
loader
Phone no. Missing!

Enter phone no. to receive critical updates and urgent messages !

Attach file

Error goes here

Files Missing!

Please upload all relevant files for quick & complete assistance.

Guaranteed Higher Grade!
Free Quote
wave

a. Choose one of the suggested candidate design patterns that you think best solves the problem. Justify the applicability of your choice. You need to research on various patterns and come up with your choices and justifications.
    
b. Applying scientific principles identify the participants for incorporating the chosen design pattern and modify the class diagram of the use case to show their relationships.
    
c. Critically analyze the patterns and list two benefits of incorporating the design pattern, with respect to the problem. 

Abstract Factory Pattern

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 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.

Factory Method Pattern

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. 

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 */ }

            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

        }

    }

}

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;

            }

        }

        System.out.println(allTotal);

    }

}

Third Implementation of Strategy Pattern for computePrice in Shopping Cart.

public class SCart {

   protected Dictionary<Product, int> theItems;

Singleton Pattern

   // 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 += "nn Total: " + totalOfCart();

      return indivd;

   }

}

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 {

    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

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;

            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.

Builder Pattern

public interface MethodOfPay {

  public boolean payUp(double theAmount);

The below object of payment is concrete as is implemented as Visa.

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.

@Test

  public void payUpThroughVisa() {

    SCart theInstance = new SCart();

    Item one = new Item("milk", 2.43);

    theInstance.appendItem(one);

    Item two = new Item("sugar", 5.99);

    theInstance.appendItem(two);

    Date theDateOfExp = getTheDateofExp();

    MethodOfPay visa1 = new Visa("JohnDoe", "abcdefghijklmnop",theDateOfExp);

    boolean theResult = theInstance.payUp(visa1);

    affirmTruth(theResult);

  }

  private Date getTheDateofExp () {

    Calendar theCal = Calendar.getInstance();

    theCal.clear();

    theCal.set(2018, Calendar.OCTOBER,9);

    return theCal.getTime();

  }

As depicted by the code above, it is used to create the checkOut after adding in the shopping cart a number of items. The newly created MethodOfPayment is made as a kind of Visa object, hence, put in to the checkOut (MethodOfPayment theMethod) subroutine. The latter makes the core subject of this paper’s enquiry. Alternatively, a MasterCard object could have been created and directly implemented by replacing it for Visa. Therefore, a Strategy Pattern’s definition is used in java Spring as the entirely used technology as shown below:

@Component

public class SpringCart{

  private final List<Item> theItems;

  @Autowired

  @Qualifier("Visa")

  private MethodOfPayment theMethod;

  public SpringCart() {

    theItems = new ArrayList<Item>();

  }

  public void appendItem(Item theItem) {

    theItems.add(theItem);

  }

  public double computeCost() {

    double theTotal = 0.0;

    for (Item theItem : theItems) {

      theTotal += theItem.getPrice();

    }

    return total;

  }

  public boolean payUp() {

    double theCost = computeCost();

    return method.payUp(theCost);

  }

}

In the above code, a differentiation is made amid it and the demonstrated implementation of the Visa class, equally interposed using Spring. The latter class is loaded up using the annotation @Autowired and makes the strategy pattern most popular.

References

Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design Patterns : Elements of Reusable Object-Oriented Software, Addison Wesley, 1995.

Smith, Ben. Object-Oriented Programming. Advanced ActionScript 3. Apress, pp63-69, 2015 .

Cite This Work

To export a reference to this article please select a referencing stye below:

My Assignment Help. (2021). Creational Design Patterns: Abstract Factory, Singleton, Builder, Factory Method, And Prototyping. Retrieved from https://myassignmenthelp.com/free-samples/mits4002-object-oriented-software-development/factory-method.html.

"Creational Design Patterns: Abstract Factory, Singleton, Builder, Factory Method, And Prototyping." My Assignment Help, 2021, https://myassignmenthelp.com/free-samples/mits4002-object-oriented-software-development/factory-method.html.

My Assignment Help (2021) Creational Design Patterns: Abstract Factory, Singleton, Builder, Factory Method, And Prototyping [Online]. Available from: https://myassignmenthelp.com/free-samples/mits4002-object-oriented-software-development/factory-method.html
[Accessed 22 July 2024].

My Assignment Help. 'Creational Design Patterns: Abstract Factory, Singleton, Builder, Factory Method, And Prototyping' (My Assignment Help, 2021) <https://myassignmenthelp.com/free-samples/mits4002-object-oriented-software-development/factory-method.html> accessed 22 July 2024.

My Assignment Help. Creational Design Patterns: Abstract Factory, Singleton, Builder, Factory Method, And Prototyping [Internet]. My Assignment Help. 2021 [cited 22 July 2024]. Available from: https://myassignmenthelp.com/free-samples/mits4002-object-oriented-software-development/factory-method.html.

Get instant help from 5000+ experts for
question

Writing: Get your essay and assignment written from scratch by PhD expert

Rewriting: Paraphrase or rewrite your friend's essay with similar meaning at reduced cost

Editing: Proofread your work by experts and improve grade at Lowest cost

loader
250 words
Phone no. Missing!

Enter phone no. to receive critical updates and urgent messages !

Attach file

Error goes here

Files Missing!

Please upload all relevant files for quick & complete assistance.

Plagiarism checker
Verify originality of an essay
essay
Generate unique essays in a jiffy
Plagiarism checker
Cite sources with ease
support
Whatsapp
callback
sales
sales chat
Whatsapp
callback
sales chat
close