gpt4 book ai didi

java - 策略设计模式

转载 作者:行者123 更新时间:2023-12-01 18:57:57 25 4
gpt4 key购买 nike

大家好,我正在尝试实现策略模式,但我无法在具体类中设置金额,我的意思是,金额与与接口(interface)有关系的辅助类中的金额相同。我尝试使用构造函数以及 setter 和 getter 方法设置值,但它不起作用,如果您可以查看并提供一些反馈,那就太好了。这是代码。

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;
}
}

所以当我测试它时它返回值------------------------------------ - 收件人:Oracle 发件人:Easyflap(英国) 金额:500.00 美元----------------------------------------------------这是来自 Customer 类中的 getInvoice 方法,当我尝试修改 AmericanInvoice 中的金额时,它不起作用。

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);
}
}

最佳答案

您实际上并没有调用策略对象本身的任何方法本身!

关于java - 策略设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13324237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com