【设计模式】策略模式设计-电影票打折功能

任务二:使用策略模式设计电影票打折功能

某电影院售标系统为不同类型的用户提供了不同的打折方式(Discount) ,学生凭学生证可享受8折优惠**(StudentDiscount),儿童可享受减免10元的优惠 (ChildrenDiscount),VIP用户除享受半价优惠外还可以进行积分(VIPDiscount)**。使用策略模式设计该系统。

UML-class

i

1

java 复制代码
* @ClassName: Ticket  * @Description: TODO  * @Author ZSC  * @Date 2023/12/4 11:32  * @Version 1.0 public class Ticket {

    private double price;
    private Discount discount;

    public double getPrice() {
        return discount.calculate(this.price);
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public void setDiscount(Discount discount) {
        this.discount = discount;
    } }

2

java 复制代码
public interface Discount {
    public double calculate(double price);
}

3

java 复制代码
    @Override
    public double calculate(double price) {
        return price-10;
    } }

public class StuDiscount implements Discount{
    @Override
    public double calculate(double price) {
        return price*0.8;
    } }


public class VIPDiscount implements Discount{
    @Override
    public double calculate(double price) {
        System.out.println("提示:增加积分!");
        return price*0.5;
    } }

4

java 复制代码
public class TicketMain {
    public static void main(String[] args) {
        // discout
        double disPrice;
        Ticket ticket = new Ticket();
        // set price
        ticket.setPrice(66.66);


        // stu
        Discount stuDiscount = new StuDiscount();
        ticket.setDiscount(stuDiscount);
        disPrice = ticket.getPrice();
        System.out.println("stu--折后价格为:"+disPrice);

        // chil
        Discount chilDiscount = new ChilDiscount();
        ticket.setDiscount(chilDiscount);
        disPrice = ticket.getPrice();
        System.out.println("childen--折后票价为:"+disPrice);
        System.out.println("==========================");
        // VIP
        Discount vipDiscount = new VIPDiscount();
        ticket.setDiscount(vipDiscount);
        disPrice = ticket.getPrice();
        System.out.println("VIP会员---折后票价为:"+disPrice);
    }
}

reference

【[参考文献]】

相关推荐
码界奇点4 小时前
Java设计模式精讲从基础到实战的常见模式解析
java·开发语言·设计模式·java-ee·软件工程
Charles_go6 小时前
41、C#什么是单例设计模式
java·设计模式·c#
ZHE|张恒6 小时前
设计模式实战篇(六):装饰器模式 —— 让系统具备“可生长能力”的架构思想
设计模式·装饰器模式
蓝桉~MLGT10 小时前
Python学习历程——文件
python·学习·策略模式
孟祥_成都10 小时前
下一代组件的奥义在此!headless 组件构建思想探索!
前端·设计模式·架构
颜酱17 小时前
理解编程的设计原则(前端角度)
设计模式
Wild_Pointer.21 小时前
设计模式实战精讲:全景目录
设计模式·设计规范
一叶飘零_sweeeet1 天前
深度拆解汽车制造系统设计:用 Java + 设计模式打造高扩展性品牌 - 车型动态生成架构
java·设计模式·工厂设计模式
阿波罗尼亚1 天前
设计原则(一)Head First设计模式
设计模式
ZHE|张恒2 天前
设计模式实战篇(五):责任链模式 — 把复杂审批/过滤流程变成可组合的“传递链”
设计模式·责任链模式