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

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

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

[参考文献](http://t.csdnimg.cn/8nlzt)

相关推荐
YHL9 小时前
🎯 JavaScript 单例模式(Singleton Pattern)—— 从理论到实战
javascript·设计模式
2401_8685347811 小时前
网络环境规划核心考点全梳理
网络·设计模式
feiyu_gao15 小时前
Cocreation Framework:一套给所有人的 AI 协作思考系统
设计模式·aigc·ai编程
善良勤劳勇敢而又聪明的老杨2 天前
【AI编程系列】MCP 常用设计模式解读
设计模式·ai编程
geovindu2 天前
java: Strategy Pattern
java·开发语言·后端·设计模式·策略模式·行为模式
码匠许师傅2 天前
【设计模式精讲】29.行为型模式总结与对比(Behavioral Patterns Summary)
c++·设计模式·uml
geovindu2 天前
CSharp: Observer Pattern
开发语言·后端·观察者模式·设计模式·c#·.netcore·行为模式
geovindu3 天前
CSharp: Strategy Pattern
开发语言·后端·c#·.net·.netcore·策略模式·行为模式
YHHLAI3 天前
NestJS 后端开发实战:从设计模式到 CRUD 全栈
设计模式
2401_868534783 天前
长远目标 Long-term Goal 老题沿用
设计模式·需求分析