装饰者模式的运用
实 验 报 告 实验二 装饰者模式的运用一、实验目的:装饰者模式动态地将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案。在熟悉装饰者模式相关理论知识的基础上,使用装设者模式实现米线店结账小程序。二、实验要求:使用装饰者模式实现米线店结账程序,要求如下:1. 米线有三种,干浆、酸浆和水米线。2. 配料有三种,豆腐、鸡蛋、牛肉,今后还会更多。3. 客户可疑随心所欲的要各种米线搭配各种配料,配料可以加同一种加多份,或者不同种加多份。1、 设计并绘制该程序的类图;2、 依照设计的类图使用Java语言编写代码,并实现该程序;3、 除了核心的模式相关类实现外,提供测试环境,按照难度高低,分别是:a) 控制台程序,Client硬编码初始化模式和测试环境,运行结果文本输出;b) 控制台程序,Client初始化测试环境,并根据用户输入运算,运行结果文本输出;c) 设计并实现用户UI,Client初始化测试环境,并根据用户在UI控件上的输入运算,运行结果文本输出;三、实验内容:类图代码抽象类public abstract class Ricenoodlepublic String descrption="米线"public abstract double cost();public String getDescrption() return descrption;基类public class Dry_rice extends Ricenoodlepublic Dry_rice()this.descrption="干浆米线"public double cost() return 5;public class Wintercherry_rice extends Ricenoodlepublic Wintercherry_rice()this.descrption="酸浆米线"public double cost() return 6; public class Water_rice extends Ricenoodlepublic Water_rice()this.descrption="水米线"public double cost() return 6;配料装饰类public abstract class CondimentDecorator extends Ricenoodlepublic abstract String getDescrption();配料public class Tofu extends CondimentDecoratorRicenoodle r;public Tofu(Ricenoodle r)this.r=r;public String getDescrption() return r.getDescrption()+"加豆腐"public double cost() return r.cost()+2;public class egg extends CondimentDecoratorRicenoodle r;public egg(Ricenoodle r)this.r=r;public String getDescrption() return r.getDescrption()+"加鸡蛋"public double cost() return r.cost()+1.5;public class beef extends CondimentDecoratorRicenoodle r;public beef(Ricenoodle r)this.r=r;public String getDescrption() return r.getDescrption()+"加牛肉"public double cost() return r.cost()+4;订单测试import java.util.Scanner;public class test public static void main(String args) Ricenoodle order=new Ricenoodle3 ;Scanner sc = new Scanner(System.in);order0=new Dry_rice();order1=new Wintercherry_rice();order2=new Water_rice();System.out.println("输入选项选择米线种类 1 干浆米线,2 酸浆米线,3 水米线");int mi =sc.nextInt();System.out.println("您购买了一份"+ordermi-1.getDescrption();for(int i=0;i<2;)System.out.println("输入选项选择调料 1 豆腐,2鸡蛋,3牛肉,4不加");int ve =sc.nextInt();if(ve=1)ordermi-1=new Tofu(ordermi-1);System.out.println("当前订单为"+ordermi-1.getDescrption();else if(ve=2)ordermi-1=new egg(ordermi-1);System.out.println("当前订单为"+ordermi-1.getDescrption();else if(ve=3)ordermi-1=new beef(ordermi-1);System.out.println("当前订单为"+ordermi-1.getDescrption();elsei=4;System.out.println("是否还要加调料 1 yes 2no");int k=sc.nextInt();if(k=1)i=1;elsei=4;sc.close();System.out.println("您点的单为"+ordermi-1.getDescrption()+"n价格为:"+ordermi-1.cost();运行结果四、实验总结:通过本次实验,加深了对装饰者模式意图,使用场景以及使用效果的理解,提升了编程能力。 指导教师签名: