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

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

某电影院售标系统为不同类型的用户提供了不同的打折方式(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

【[参考文献]】

相关推荐
wangchunting3 小时前
Java设计模式
java·单例模式·设计模式
孟陬18 小时前
国外技术周刊 #3:“最差程序员”带动高效团队、不写代码的创业导师如何毁掉创新…
前端·后端·设计模式
砍光二叉树1 天前
【设计模式】结构型-代理模式
设计模式·系统安全·代理模式
新缸中之脑1 天前
AI智能体五大设计模式
人工智能·机器学习·设计模式
砍光二叉树1 天前
【设计模式】结构型-装饰器模式
设计模式·装饰器模式
han_1 天前
JavaScript设计模式(三):代理模式实现与应用
前端·javascript·设计模式
我的offer在哪里1 天前
POM 设计模式深度解析|博客视角:从原理到落地,让自动化测试脚本 “活” 起来
设计模式
程序员Terry1 天前
Java 代理模式:从生活中的"中介"到代码中的"代理人"
后端·设计模式
砍光二叉树1 天前
【设计模式】结构型-适配器模式
设计模式·适配器模式
Yu_Lijing1 天前
基于C++的《Head First设计模式》笔记——蝇量模式
c++·笔记·设计模式