行为型设计模式随堂测验

文章通过一个Java代码示例展示了如何使用策略模式来处理不同类型的折扣算法,如金卡、钻石卡和银卡客户的不同折扣。策略模式允许在运行时动态选择不同的算法,提高了代码的可维护性和扩展性,避免了大量条件语句的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
1.

package celue;

class HairCut {
   private Discount discount;

   // 设置客户类型
   public void setCustomerType(Discount count) {
       discount = count;
   }

   // 计算折后价
   public double getFinalPrice(double price) {
       return discount.calculate(price);
   }
}



package celue;

// 折扣接口
interface Discount {
   double calculate(double price);
}

package celue;

// 金卡客户6折优惠
class GoldDiscount implements Discount {
   public double calculate(double price) {
       return price * 0.6;
   }
}
package celue;

// 钻石卡客户5折优惠
class DiamondDiscount implements Discount {
   public double calculate(double price) {
       return price * 0.5;
   }
}
package celue;

// 银卡客户7.5折优惠
class SilverDiscount implements Discount {
   public double calculate(double price) {
       return price * 0.75;
   }
}
package celue;

public class Client {
   public static void main(String[] args) {
       HairCut hairCut = new HairCut();

       // 读取配置文件获取客户类型
       Object customerType ;
       customerType=XMLUtil.getBean("GoldDiscount");
       hairCut.setCustomerType((Discount) customerType);

       double originalPrice = 100.0; // 原价
       double finalPrice = hairCut.getFinalPrice(originalPrice); // 折后价

       System.out.println("Original price: " + originalPrice);
       System.out.printf("Discounted price for %s customer: %.2f", customerType, finalPrice);
   }
}

策略模式是一种行为型模式,它定义了一系列算法(策略),并将每个算法封装起来,使它们可以相互替换,而且替换过程可以在不改变调用它们的客户端代码的情况下进行。策略模式的优点包括:

易于扩展和维护:添加新的算法或修改现有的算法时,只需要编写新的策略类或修改已有的策略类即可,不会影响到其他代码。

避免使用大量的条件语句:通过将具体的算法封装成策略类,避免了 if-else 或 switch-case 等复杂的条件语句,使得代码更加简洁、易读、易于维护。

可以提高代码的复用性:策略类可以被客户端程序复用,或者在多个项目中共享,从而减少代码重复。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

万伏小太阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值