有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何实现基于松散耦合的代码散播主方法

休闲代码解释了松耦合的概念。我想实现添加项目(包括价格和数量)的主要方法,并用销售税计算总价。我如何实现主方法

class ShopingCartEntry {

    public float price;
    public int quantity;

    public float getTotalPrice() {
        return price * quantity;
    }
}

class ShopingCartContents {

    public ShopingCartEntry[] items;

    public float getTotalPrice() {
        float totalPrice = 0;
        for (ShopingCartEntry item : items) {
            totalPrice += item.getTotalPrice();
        }
        return totalPrice;
    }
}

class Order {

    private ShopingCartContents cart;
    private float salesTax;

    public Order(ShopingCartContents cart, float salesTax) {
        this.cart = cart;
        this.salesTax = salesTax;
    }

    public float orderTotalPrice() {
        return cart.getTotalPrice() * (1.0f + salesTax);
    }
}

public class LooseCoupling {

    public static void main(String[] args) {

    }
}

共 (1) 个答案

  1. # 1 楼答案

    首先,我认为你的代码不完整

    其次,下面是实现的伪代码

    class ShopingCartEntry {
    
        public float price;
        public int quantity;
    
        public float getTotalPrice() {
            return price * quantity;
        }
    
    
        // either add a constructor or getter / setter to initialize price & quantity
    }
    
    class ShopingCartContents {
    
        public ShopingCartEntry[] items; // instead of an array you should have a parameterized constructor 
    
        public float getTotalPrice() { // pass a list of ShopingCartEntry
            float totalPrice = 0;
            for (ShopingCartEntry item : items) {
                totalPrice += item.getTotalPrice();
            }
            return totalPrice;
        }
    
    
    
    }
    
    class Order {
    
        private ShopingCartContents cart; 
        private float salesTax;
    
        // add a List<ShopingCartEntry> object
    
        public Order(ShopingCartContents cart, float salesTax) {
            this.cart = cart;
            this.salesTax = salesTax;
            // add the object to the orderList - new list
        }
    
        public float orderTotalPrice() {
            return cart.getTotalPrice() * (1.0f + salesTax); // pass the list as a parameter to cart.getTotalPrice()
        }
    
        // add a mtheod to add contents / objects to the list - name addContents to the list
    }
    
    public class LooseCoupling {
    
        public static void main(String[] args) {
            /* 1. create an object of order class - passing the item and price
             2. run a loop to add object to the order list method - addContents
             3. finally you should call oreder.orderTotalPrice() */
    
             // secondly add another method to remove objects from list
    
        }
    }