一个商场里卖的面包,如果没有会员卡,卖2块,有会员金卡卖1块5,银卡卖1块8。请写出一个计算类,包含计算面包价格的方法。
大家一起讨论。
锻炼一下面向对象的思想。。

解决方案 »

  1.   


    public interface Card {
    public String getLevel();
    }public class GoldCard implements Card { private String level="Gold_Card";
    @Override
    public String getLevel() {
    return this.level;
    } public String toString()
    {
    return "Gold_Card";
    }
    }public class SilverCard implements Card { private  String level="Silver_Card";
    @Override
    public String getLevel() {
    // TODO Auto-generated method stub
    return this.level;
    }
    public String toString()
    {
    return "Silver_Card";
    }
    }
    public class Bread {
    private double price; public Card card; public Bread(double price) {
    this.card = null;
    this.price = price;
    } public Bread(Card card, double price) {
    this.card = card;
    this.price = price;
    } public void setPrice(double price) {
    this.price = price;
    }

    public void setCard(Card card)
    {
    this.card=card;
    } public double getPrice() {
    double discountPrice = this.price;
    if (card != null) {
    if ("Gold_Card".equals(card.getLevel()))
    {
    discountPrice = 1.5;
    }
    if ("Silver_Card".equals(card.getLevel())) {
    discountPrice = 1.8;
    }
    }  return discountPrice;
    }         //没写测试类了
    public static void main(String args[]) {
    Card goldCard = new GoldCard();
    Bread bread = new Bread(goldCard, 2.0);
    System.out.println("The Bread price with " + goldCard + "is: "
    + bread.getPrice()); Bread bread1 = new Bread(2.0);
    System.out.println("The Bread price is:" + bread1.getPrice());

    Card silverCard = new SilverCard();
    Bread bread2 = new Bread(silverCard, 2.0);
    System.out.println("The Bread price with " + silverCard + "is: "
    + bread2.getPrice()); }}希望大家对我写的代码 指出写得不合理的地方 谢谢
      

  2.   

    第一反应是要用 strategy pattern