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

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

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

【[参考文献]】

相关推荐
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
烛阴1 天前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript
李广坤1 天前
工厂模式
设计模式
幂简集成explinks2 天前
e签宝签署API更新实战:新增 signType 与 FDA 合规参数配置
后端·设计模式·开源
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
努力也学不会java2 天前
【设计模式】抽象工厂模式
java·设计模式·oracle·抽象工厂模式
青草地溪水旁2 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁2 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
Magnetic_h3 天前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa