简体   繁体   中英

Java Factory Method Pattern

Please would someone be able to help me with understanding how I'm meant to use factory method pattern to create a new (inherited) version of a class B, which then overrides a method with a new method that then returns an instance of class A. (And potentially a few other things not relevant yet though).

Not asking anyone to do this for me just would really love if anyone could steer me in the right direction as I know I can do it, but finding that place to start is the problem plus the deadline is very close so every little helps.

Explanation->

The program we are modifying is one premade to do with a shop using guis. Our task is to modify it and improve it. The initial task is to merge repeated product items into a single request for multiple products; ie currently outputs in the console like this;

0003 Toaster ( 1) £ 19.99

0003 Toaster ( 1) £ 19.99

but should look like;

0003 Toaster ( 2) £ 38.98

The problem is this has to be done by using inheritance and the entire program has a ridiculous amount of classes in it.

Our first task is to modify Class B which extends Class A. (It also says we will have to create a new instance of Class B rather than Class A). We should do this by using the Factory Method Pattern to create a new (inherited) version of Class C that overrides the method 'makeBasket' with a new method which then returns an instance of Class B. All without actually changing any of the code in Class C.

I think the code should look something like this;

public class BetterCashierModel extends CashierModel {
@Override
protected Basket makeBasket()
{
return new BetterBasket();
}
}

However I really am not sure and have no clue which class I'm meant to put this code in. The way the work is worded implies it should be able to fit in class B somewhere but I really can't work it out.

This is the class we are told to edit for this particular task

The things commented out are what I've added for the sake of being able to tell what was already given to me.

package catalogue;

import java.io.Serializable;
import java.util.Collections;

 public class BetterBasket extends Basket implements Serializable
{
  private static final long serialVersionUID = 1L;


  // This is where I need to override the method 'add' in the class 'Basket'.
  // as well as create the newBasket i previously mentioned i suspect#

  // @Override
  // public boolean add( Product pr)
  // {
  // return super.add( pr ); 
}
}

Sorry if this is confusing or not allowed, just would really love some help right now thanks :) (Edits Formatting - Sorry )

我认为您只需要使用一种逻辑来覆盖BetterBasket类中的add ,该逻辑将首先检查输入的Product是否已存储,您可能应该使用Basket的受保护API。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM