package helloworld; interface Visitor{ public double visit(AmmeterElement elment); } abstract class AmmeterElement{ public abstract void accept(Visitor v); public abstract double showElectricAmount(); public abstract void setElectricAmount(double n); } class HomeAmmeterVisitor implements Visitor{ public double visit( AmmeterElement ammeter){ double charge=0; double unitOne=0.6,unitTwo=1.05; int basic = 6000; double n=ammeter.showElectricAmount(); if(n<=basic) { charge = n*unitOne; } else { charge =basic*unitOne+(n-basic)*unitTwo; } return charge; } } class IndustryAmmeteVisitor implements Visitor{ public double visit(AmmeterElement ammeter){ double charge=0; double unitOne=1.52,unitTwo=2.78; int basic = 15000; double n=ammeter.showElectricAmount(); if(n<=basic) { charge = n*unitOne; } else { charge =basic*unitOne+(n-basic)*unitTwo; } return charge; } } class Ammeter extends AmmeterElement{ double electricAmount; //电表的电量 public void setElectricAmount(double n) { electricAmount = n; } public void accept(Visitor visitor){ double feiyong= visitor.visit(AmmeterElement x); //让访问者访问当前元素 System.out.println("当前电表的用户需要交纳电费:"+feiyong+"元"); } public double showElectricAmount(){ return electricAmount; } } public class Main { public static void main(String args[]) { Visitor 计表员=new HomeAmmeterVisitor(); //生成按家用电标准计算电费的"计表员" Ammeter 电表=new Ammeter(); 电表.setElectricAmount(5678); 电表.accept(计表员); //调用电表的accept的方法按家用标准计算电费 计表员=new IndustryAmmeteVisitor(); //生成按工业用电标准计算电费的"计表员" 电表.setElectricAmount(5678); 电表.accept(计表员); } }修改以下代码
时间: 2024-02-14 15:11:30 浏览: 61
ALittleJava:Visitor Pattern Understanding, 数据和行为
在类Ammeter中的accept方法中,将AmmeterElement x修改为this,表示访问当前的电表元素。修改后的代码如下:
```
class Ammeter extends AmmeterElement{
double electricAmount; //电表的电量
public void setElectricAmount(double n) {
electricAmount = n;
}
public void accept(Visitor visitor){
double feiyong= visitor.visit(this); //让访问者访问当前元素
System.out.println("当前电表的用户需要交纳电费:"+feiyong+"元");
}
public double showElectricAmount(){
return electricAmount;
}
}
```
阅读全文