嗨,大家我試圖實現戰略模式,但我不能在具體的類中設置金額,我的意思是金額與助手類中具有關係的金額相同與界面。我嘗試着用構造函數和setter以及getter方法設置這個值,但是如果你可以看一看並給出一些反饋,它就會變成graet.Here就是代碼。策略設計模式
public interface InvoicingAlgorithm
{
public void getInvoice(String name, double amount);
}
public class AmericanInvoice implements InvoicingAlgorithm
{
AmericanInvoice()
{
}
//Uk: america 1 : 1.57
@Override
public void getInvoice(String name, double amount)
{
Customer customer = new Customer(name , amount * 1.57);
customer.setAmount(amount * 1.57);
customer.getInvoice();
}
}
public class Customer
{
/**
* @param name represent the name of the Customer
*/
private String name;
/**
* @param amount represent the amount of money
*/
private double amount;
/**
* @param i represents object of InvoicingAlgorithm
*/
private InvoicingAlgorithm i;
Customer(String name, double amount)
{
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public InvoicingAlgorithm getI() {
return i;
}
public void setInvoicingAlgorithm(InvoicingAlgorithm i)
{
this.i = i;
}
public String getInvoice()
{
DecimalFormat df = new DecimalFormat("#.00");
String total = "--------------------------------------TO: "
+ name + "FROM: Easyflap (UK) AMOUNT" + ":$" +
df.format(amount)
+ "--------------------------------------";
return total;
}
}
所以,當我測試它返回的值--------------------------------- ----- TO:OracleFROM:Easyflap(英國)金額:$ 500.00 ---------------------------------- ----當我嘗試修改AmericanInvoice中的金額時,它來自Customer類中的getInvoice方法,它不起作用。
測試類的AmericanInvoice
public class AmericanInvoiceTest {
/**
* Test of getInvoice method, of class AmericanInvoice.
*/
@Test
public void testGetInvoice() {
System.out.println("Producing American invoice");
final int invoiceAmount = 500;
final Customer c = new Customer("Oracle", invoiceAmount);
c.setInvoicingAlgorithm(new AmericanInvoice());
String actualOutput = c.getInvoice();
final File f = new File("actual-american.txt");
FileUtility.resetFile(f);
FileUtility.writeFile(f, actualOutput);
String expectedOutput = FileUtility.readFile(new File("expected-american.txt"));
//System.out.println(actualOutput);
//System.out.println(expectedOutput);
actualOutput = actualOutput.replaceAll("\\s", "");
expectedOutput = expectedOutput.replaceAll("\\s", "");
//System.out.println(actualOutput);
//System.out.println(expectedOutput);
assertEquals(actualOutput, expectedOutput);
}
}
所以在這個例子中策略對象是Customer類型的,不是嗎? –
不是,這是發票。您可以將一個發票類型替換爲客戶下的另一個發票類型 –