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

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

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

【[参考文献]】

相关推荐
李广坤37 分钟前
状态模式(State Pattern)
设计模式
李广坤2 小时前
观察者模式(Observer Pattern)
设计模式
李广坤3 小时前
中介者模式(Mediator Pattern)
设计模式
李广坤3 小时前
迭代器模式(Iterator Pattern)
设计模式
李广坤4 小时前
解释器模式(Interpreter Pattern)
设计模式
阿无,6 小时前
java23种设计模式之前言
设计模式
Asort7 小时前
JavaScript设计模式(八):组合模式(Composite)——构建灵活可扩展的树形对象结构
前端·javascript·设计模式
数据智能老司机7 小时前
数据工程设计模式——数据基础
大数据·设计模式·架构
笨手笨脚の10 小时前
设计模式-代理模式
设计模式·代理模式·aop·动态代理·结构型设计模式
Overboom17 小时前
[C++] --- 常用设计模式
开发语言·c++·设计模式