用多态替换条件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用多态替换条件相关的知识,希望对你有一定的参考价值。

我试图用一个例子来理解这个干净的代码实践。考虑具有折扣开关案例的类产品。我试图用多态替换switch语句。

代码之前:

class Product {
    String priceCode;
    int discount;

    Product(String priceCode) {
        setDiscount(priceCode);
    }

    public int getDiscount() {
        return discount;
    }

    public void setDiscount(String priceCode) {
        switch (priceCode) {
            case "CODE1":
                discount = // some logic;
            case "CODE2":
                discount = // some other logic;
            case "CODE3":
                discount = // some other logic;
        }
    }
}

在下面的代码中你可以看到我删除了switch语句但是我仍然有条件来创建discountStrategy的对象。我的问题是,我仍然有条件,我试图删除多态性。

代码后:

class Product {
    String priceCode;
    DiscountStrategy discountStrategy;

    Product(String priceCode) {
        setDiscount(priceCode);
    }

    public int getDiscount() {
        return discountStrategy.getDiscount();
    }

    public void setDiscount(String priceCode) {
        if (priceCode.equals("CODE1")) {
            discountStrategy = new DiscountStrategy1();
        } else if (priceCode.equals("CODE2")) {
            discountStrategy = new DiscountStrategy2();
        }
        // ...
    }
}

interface DiscountStrategy {
    public int getDiscount();
}

class DiscountStrategy1 implements DiscountStrategy {
    public int getDiscount() {
        // calculate & return discount;
    }
}

class DiscountStrategy2 implements DiscountStrategy {
    public int getDiscount() {
        // calculate & return discount;
    }
}

class DiscountStrategy3 implements DiscountStrategy {
    public int getDiscount() {
        // calculate & return discount;
    }
}

你可以通过更好地实现这个例子来帮助我理解这个概念吗?

答案

我认为Product class一定不了解折扣创建过程,它应该只使用折扣。所以,我的建议是创建一个带有Map的折扣工厂,它将包含不同的折扣实现:

class DiscountFactory {
    private static final Map<String, DiscountStrategy> strategies = new HashMap<>();
    private static final DiscountStrategy DEFAULT_STRATEGY = () -> 0;

    static {
        strategies.put("code1", () -> 10);
        strategies.put("code2", () -> 20);
    }

    public DiscountStrategy getDiscountStrategy(String priceCode) {
        if (!strategies.containsKey(priceCode)) {
            return DEFAULT_STRATEGY;
        }
        return strategies.get(priceCode);
    }
}

之后,Product类可以简化:

class Product {
    private DiscountStrategy discountStrategy;

    Product(DiscountStrategy discountStrategy) {
        this.discountStrategy = discountStrategy;
    }

    public int getDiscount() {
        return discountStrategy.getDiscount();
    }
}

功能接口允许您使用lambda表达式创建不同的实现:

interface DiscountStrategy {
    int getDiscount();
}

最后,将产品与折扣一起使用的示例:

DiscountFactory factory = new DiscountFactory();
Product product = new Product(factory.getDiscountStrategy("code1"));
另一答案

我的两分钱:你需要将参数传递给discount()方法。

一个。创建一个HashMap的静态类级别DiscountStrategy。例如:

map.put("CODE1", new DiscountStrategy1());
map.put("CODE2", new DiscountStrategy2());

湾无论您需要什么,您都可以使用:

map.get(priceCode).discount()
另一答案

这是你需要做的

    class Product {

    String priceCode;
    DiscountStrategy discountStrategy;

    HashMap<String, DiscountStrategy> map=new HashMap();

    Product(String priceCode) {
        map.put("CODE1", new DiscountStrategy1());
        map.put("CODE2", new DiscountStrategy2());
        map.put("CODE3", new DiscountStrategy3());
        setDiscount(priceCode);
    }

    public void setDiscount(String priceCode){
               discountStrategy=map.get(priceCode);
        }

    public int getDiscount() {
        return discountStrategy.getDiscount();
    }
}
另一答案

当您的示例中似乎是这种情况时,折扣策略绑定到特定的产品类型,我会在订单商品级别计算折扣。例如:

class Product {
    double basePrice;
    DiscountStrategy discountStrategy;

...

    public double getBasePrice() {
        return basePrice;
    }

    public DiscountStrategy getDiscountStrategy() {
        return discountStrategy;
    }
}

interface DiscountStrategy {
    public double calculate(int quantity, Product product);
}

class OrderItem {
    int quantity;
    Product product;

    public double getAmount() {
        DiscountStrategy ds = product.getDiscountStrategy();
        double discount = ds.calculate(quantity, product);
        return quantity*(product.getBasePrice() - discount);
    }
}

折扣策略示例:数量折扣:

class QuantityRateDiscount implements DiscountStrategy {
    static class QuantityRate {
        final int minQuantity;
        final double rate; // in %

        QuantityRate(int minQuantity, double rate) {
            this.minQuantity = minQuantity;
            this.rate = rate;
        }
    }

    QuantityRate[] rateTable;

    // rateTable must be sorted by ascending minQuantity
    QuantityRateDiscount(QuantityRate... rateTable) {
        this.rateTable = rateRable.clone();
    }

    @Override
    public double calculate(int quantity, Product product) {
        QuantityRate qr = null;
        for (QuantityRate qr2: rateTable) {
            if (qr2.minQuantity > quantity) {
                break;
            }
            qr = qr2;
        }
        if (qr != null) {
            return product.getBasePrice()*qr.rate/100.0;
        } else {
            return 0;
        }
    }
}

以上是关于用多态替换条件的主要内容,如果未能解决你的问题,请参考以下文章

用片段替换某些东西

编写高质量代码改善C#程序的157个建议——建议104:用多态代替条件语句

替换从 VAST 代码返回的多个 HLS VOD 片段

如何从主要活动中替换片段

如何在android studio中用另一个片段替换一个片段

用活动组内的另一个片段替换片段