安徽大学软件构造(设计模式)实验集

安徽大学软件构造(设计模式)实验集,第1张

安徽大学软件构造(设计模式实验

文章目录

实验一:工程方法与抽象工厂模式

实验题目目录结构实验代码

简单工厂工厂方法抽象工厂 实验二:生成器模式与原型模式的编程实现

实验题目目录结构实验代码 实验三:装饰模式的编程实现

实验题目目录结构实现代码 实验四:组合模式与责任链模式

实验题目实验代码 实验五:解释器模式

实验题目目录结构实验代码 大作业

题目项目目录结构实现代码UML图 二

题目项目目录结构实现代码UML图 三

题目项目目录结构实现代码UML图

实验一:工程方法与抽象工厂模式 实验题目

利用工厂方法和抽象工厂模式模拟实现服装工厂生产衣服的过程,具体内容如下:

现有三种品牌A、B和C的夹克,分别利用简单工厂模式和工厂方法模式实现生产各种品牌夹克的代码(即打印“生产A品牌夹克”之类的句子即可)

A、B和C各品牌除了生产夹克,还可以再生产裤子,利用抽象工厂模式实现各品牌夹克与裤子生产过程。

目录结构
D:.
└─com
    └─longstudy
        ├─abstractfactory
        │  ├─factory
        │  │  │  AbstractFactory.java
        │  │  │
        │  │  └─impl
        │  │          AFactory.java
        │  │          BFactory.java
        │  │          CFactory.java
        │  │
        │  ├─jacket
        │  │  │  Jacket.java
        │  │  │
        │  │  └─impl
        │  │          JacketA.java
        │  │          JacketB.java
        │  │          JacketC.java
        │  │
        │  └─trouser
        │      │  Trouser.java
        │      │
        │      └─impl
        │              TrouserA.java
        │              TrouserB.java
        │              TrouserC.java
        │
        ├─factory
        │  │  JacketFactory.java
        │  │
        │  └─jacket
        │      │  Jacket.java
        │      │
        │      └─impl
        │              JacketA.java
        │              JacketB.java
        │              JacketC.java
        │
        └─factorymethod
            ├─factory
            │  │  JFactory.java
            │  │
            │  └─impl
            │          JacketAFractory.java
            │          JacketBFractory.java
            │          JacketCFractory.java
            │
            └─jacket
                │  Jacket.java
                │
                └─impl
                        JacketA.java
                        JacketB.java
                        JacketC.java
实验代码 简单工厂
public interface Jacket {
    void printJacket();
}
public class JacketA implements Jacket {
    @Override
    public void printJacket() {
        System.out.println("生产夹克A");
    }
}
public class JacketB implements Jacket {
    @Override
    public void printJacket() {
        System.out.println("生产夹克B");
    }
}
public class JacketC implements Jacket {
    @Override
    public void printJacket() {
        System.out.println("生产夹克C");
    }
}
public class JacketFactory {
    public Jacket getJacket(String jacket){
        if(jacket==null){
            return null;
        }
        if (jacket.equals("A")){
            return new JacketA();
        }else if(jacket.equals("B")){
            return new JacketB();
        }else if(jacket.equals("C")){
            return new JacketC();
        }
        return null;
	}
}

测试:

public class JacketFactory {
    public Jacket getJacket(String jacket){
        if(jacket==null){
            return null;
        }
        if (jacket.equals("A")){
            return new JacketA();
        }else if(jacket.equals("B")){
            return new JacketB();
        }else if(jacket.equals("C")){
            return new JacketC();
        }
        return null;
    }
}

工厂方法
public interface JFactory {
    Jacket createJacket();
}
public class JacketAFractory implements JFactory {
    @Override
    public Jacket createJacket() {
        return new JacketA();
    }
}
public class JacketBFractory implements JFactory {
    @Override
    public Jacket createJacket() {
        return new JacketB();
    }
}
public class JacketCFractory implements JFactory {
    @Override
    public Jacket createJacket() {
        return new JacketC();
    }
}

测试:

public class MyTest2 {
    @Test
    public void factoryMethodTest(){
        JFactory afactoty = new JacketAFractory();
        Jacket a = afactoty.createJacket();
        System.out.println(a.getClass());
        a.printJacket();

        JFactory bfactoty = new JacketBFractory();
        Jacket b = bfactoty.createJacket();
        System.out.println(b.getClass());
        b.printJacket();

        JFactory cfactoty = new JacketCFractory();
        Jacket c = cfactoty.createJacket();
        System.out.println(c.getClass());
        c.printJacket();
    }
}

抽象工厂
public abstract class AbstractFactory {
    public abstract Jacket getJacket();
    public abstract Trouser getTrouser();
}
public class AFactory extends AbstractFactory {
    @Override
    public Jacket getJacket() {
        return new JacketA();
    }

    @Override
    public Trouser getTrouser() {
        return new TrouserA();
    }
}
public class BFactory extends AbstractFactory {
    @Override
    public Jacket getJacket() {
        return new JacketB();
    }

    @Override
    public Trouser getTrouser() {
        return new TrouserB();
    }
}
public class CFactory extends AbstractFactory {
    @Override
    public Jacket getJacket() {
        return new JacketC();
    }

    @Override
    public Trouser getTrouser() {
        return new TrouserC();
    }
}

测试:

public class MyTest3 {
    @Test
    public void abstractFactoryTest(){
        try{
            AbstractFactory afactory = new AFactory();
            afactory.getJacket().printJacket();
            afactory.getTrouser().trouserPrint();
            AbstractFactory bfactory = new BFactory();
            bfactory.getJacket().printJacket();
            bfactory.getTrouser().trouserPrint();
            AbstractFactory cfactory = new CFactory();
            cfactory.getJacket().printJacket();
            cfactory.getTrouser().trouserPrint();
        }catch (NullPointerException e){
            e.printStackTrace();
        }
    }
}

实验二:生成器模式与原型模式的编程实现 实验题目

使用生产器模式模拟实现IBM电脑的生产,其中IBM电脑的主要结构用如下表示:

class IBM{
	string monitor = "IBM的显示器";
    string keyboard = "IBM的键盘";
    string mouse = "IBM的鼠标";
    Motherboard* MB;
    void display();
}

其中MB是一个主板类,其主要接哦股如下:

class Motherboard{
    string CPU;
    string RAM;
}

即主板包含CPU和RAM,display是一个打印各个组件的函数,主要用于检查是否生产正确。

建造顺序为先生产主板,再一次生产显示器、键盘、鼠标。

使用生产器模式生产出第一台IBM电脑后,利用原型模式,将该电脑再赋值两台。

目录结构
│  Director.java
│  IBMProduct.java
│  Main.java
│  Motherboard.java
└─builder
        Builder.java
        ConcreteBuilderPlan.java
实验代码

Motherboard类:

public class Motherboard {
    private String CPU;
    private String RAM;

    public Motherboard() {
    }

    public Motherboard(String CPU, String RAM) {
        this.CPU = CPU;
        this.RAM = RAM;
    }

    @Override
    public String toString() {
        return "Motherboard{" + CPU + "," + RAM  + '}';
    }

    public Motherboard clone(){
        Motherboard motherboard = new Motherboard();
        motherboard.setCPU(this.CPU);
        motherboard.setRAM(this.RAM);
        return motherboard;
    }

    public String getCPU() {
        return CPU;
    }

    public void setCPU(String CPU) {
        this.CPU = CPU;
    }

    public String getRAM() {
        return RAM;
    }

    public void setRAM(String RAM) {
        this.RAM = RAM;
    }
}

IBMProduct:

public class IBMProduct {
    private String monitor;
    private String keyboard;
    private String mouse;
    private Motherboard MB;

    public IBMProduct() {
    }

    public IBMProduct clone(){
        IBMProduct ibmProduct = new IBMProduct();
        ibmProduct.setKeyboard(this.keyboard);
        ibmProduct.setMonitor(this.monitor);
        ibmProduct.setMouse(this.mouse);
        Motherboard mb = MB.clone();
        ibmProduct.setMB(mb);
        return ibmProduct;
    }

    public void show() {
        System.out.println("IBM product:");
        System.out.println(this.MB.getCPU()+","+this.MB.getRAM());
        System.out.println(this.monitor);
        System.out.println(this.keyboard);
        System.out.println(this.mouse);
    }

    public void setMonitor(String monitor) {
        this.monitor = monitor;
    }

    public void setKeyboard(String keyboard) {
        this.keyboard = keyboard;
    }

    public void setMouse(String mouse) {
        this.mouse = mouse;
    }

    public void setMB(Motherboard MB) {
        this.MB = MB;
    }
}

Builder接口:

public interface Builder {
    void BuildMonitor();
    void BuildKeyboard();
    void BuildMouse();
    void BuildMotherBoard();
    default IBMProduct getResult(){
        return null;
    }
}

Builder接口的实现类:

public class ConcreteBuilderPlan implements Builder {
    private IBMProduct product = new IBMProduct();

    @Override
    public void BuildMonitor() {
        product.setMonitor("IBM----显示器");
    }

    @Override
    public void BuildKeyboard() {
        product.setKeyboard("IBM----显示器");
    }

    @Override
    public void BuildMouse() {
        product.setMouse("IBM----鼠标");
    }

    @Override
    public void BuildMotherBoard() {
        Motherboard motherboard = new Motherboard();
        motherboard.setCPU("IBM----CPU");
        motherboard.setRAM("IBM----RAM");
        product.setMB(motherboard);
    }

    @Override
    public IBMProduct getResult() {
        return product;
    }
}

指挥者类:

public class Director {
    public void construct(Builder builder){
        builder.BuildMotherBoard();
        builder.BuildMonitor();
        builder.BuildKeyboard();
        builder.BuildMouse();
    }
}

测试:

public class Main {
    public static void main(String[] args) {
        Director director = new Director();
        ConcreteBuilderPlan concreteBuilderPlan = new ConcreteBuilderPlan();
        director.construct(concreteBuilderPlan);
        IBMProduct result = concreteBuilderPlan.getResult();
        result.show();

        System.out.println("*************原型模式***************");

        IBMProduct clone = result.clone();
        clone.setMouse("惠普----鼠标");
        clone.setKeyboard("华硕----键盘");
        clone.setMouse("惠普----鼠标");
        clone.setMB(new Motherboard("英特尔----CPU","AMD----RAM"));
        clone.show();

        System.out.println("*************原型模式2***************");

        IBMProduct clone2 = result.clone();
        clone2.setMouse("AMD----鼠标");
        clone2.setKeyboard("AMD----键盘");
        clone2.setMonitor("AMD----键盘");
        clone2.setMouse("AMD----鼠标");
        clone2.setMB(new Motherboard("AMD----CPU","AMD----RAM"));
        clone2.show();
    }
}
实验三:装饰模式的编程实现 实验题目

利用工厂方法模式实例化两个汽车类,例如丰田和沃尔沃。

对于这两种初始的汽车类(丰田和沃尔沃),利用装饰模式分别给它们添加新功能,其中丰田可以导航和自动驾驶,沃尔沃可以导航和语音控制。

目录结构
G:.
│  Client.java
├─car
│      Car.java
│      Toyota.java
│      Volvo.java
├─decorator
│      NewToyota.java
│      NewVolvo.java
│      ToyotaDecorator.java
│      VolvoDecorator.java
└─factory
        CarFactory.java
        ToyotaFactory.java
        VolvoFactory.java
实现代码

实例:

public interface Car {
    void printCar();
}
public class Toyota implements Car {
    @Override
    public void printCar() {
        System.out.println("这是一辆Toyota");
    }
}
public class Volvo implements Car {
    @Override
    public void printCar() {
        System.out.println("这是一辆Volvo");
    }
}

工厂:

public interface CarFactory {
    Car createCar();
}
public class ToyotaFactory implements CarFactory {
    @Override
    public Toyota createCar() {
        return new Toyota();
    }
}
public class VolvoFactory implements CarFactory{
    @Override
    public Volvo createCar() {
        return new Volvo();
    }
}

装饰器:

public interface NewToyota extends Car {
    // 导航
    void navigation();
    // 自动驾驶
    void autopilot();
}
public interface NewVolvo extends Car {
    // 导航
    void navigation();
    // 语音控制
    void voiceControl();
}
public class ToyotaDecorator implements NewToyota {
    private final Car car;

    public ToyotaDecorator(Car car) {
        this.car = car;
    }

    @Override
    public void navigation() {
        System.out.println("添加功能---导航");
    }

    @Override
    public void autopilot() {
        System.out.println("添加功能---自动驾驶");
    }

    @Override
    public void printCar() {
        car.printCar();
    }
}
public class VolvoDecorator implements NewVolvo {
    private final Car car;

    public VolvoDecorator(Car car) {
        this.car = car;
    }

    @Override
    public void navigation() {
        System.out.println("添加功能---导航");
    }

    @Override
    public void voiceControl() {
        System.out.println("添加功能---语音控制");
    }

    @Override
    public void printCar() {
        car.printCar();
    }
}

客户端调用:

public class Client {
    public static void main(String[] args) {
        
        // 工厂生产
        ToyotaFactory toyotaFactory = new ToyotaFactory();
        Toyota toyota = toyotaFactory.createCar();
        // 装饰
        ToyotaDecorator toyotaDecorator = new ToyotaDecorator(toyota);
        toyotaDecorator.printCar();
        toyotaDecorator.autopilot();
        toyotaDecorator.navigation();
        
        VolvoFactory volvoFactory = new VolvoFactory();
        Volvo volvo = volvoFactory.createCar();

        VolvoDecorator volvoDecorator = new VolvoDecorator(volvo);
        volvoDecorator.printCar();
        volvoDecorator.navigation();
        volvoDecorator.voiceControl();
    }
}

实验四:组合模式与责任链模式 实验题目

根据下图,利用组合模式构建该公司的结构。

即总公司下设上海华东分公司,华东分公司下设南京办事处和杭州办事处。其中,各级分公司均设有人力资源部和财务部。

利用组合模式构建好该结构后,利用职责链模式处理各地员工加薪请求。

例如,一南京员工提出加薪请求,如果加薪不超过1000元,南京办事处即可批准;如果超过1000元,则上报华东分公司,如果2000元以内,则批准;超过则上报北京总公司,如果不超过3000元,则总公司批准,否则拒绝。

实验代码
public interface Component {
    void add(Component c);
    void remove(Component c);
    void print(int depth);
    void handlerRequest(int request);
}
public class Department implements Component{
    private String name;
    // 最低工资和最高工资区间
    private int low;
    private int high;
    private Component successor;
    private List departmentsList = new linkedList<>();

    public Department() { }

    public Department(String name) {
        this.name = name;
    }

    // 设置薪资上下限
    public void setBound(int low,int high){
        this.low=low;
        this.high=high;
    }

    public void setSuccessor(Component c){
        this.successor=c;
    }

    @Override
    public void add(Component c) {
        this.departmentsList.add(c);
    }

    @Override
    public void remove(Component c) {
        this.departmentsList.remove(c);
    }

    // 递归打印构建的树
    public void print(int depth){
        for(int i=1;i<=depth;i++){
            System.out.print("--");
        }
        System.out.println(this.name);
        for (Component department : departmentsList) {
            department.print(depth+1);
        }
    }

    @Override
    public void handlerRequest(int request) {
        if(request>=low && request<=high){
            System.out.println(this.name+">>>处理请求,加薪:"+request);
        }else if(successor!=null){
            System.out.println(this.name+">>>没有权限");
            successor.handlerRequest(request);
        }else{
            System.out.println(this.name+">>>就是不给你加薪");
        }
    }
}

客户端测试:

public class Client {
    public static void main(String[] args) {
        Department node1 = new Department("北京公司总部");
        Department node2 = new Department("人力资源部");
        Department node3 = new Department("上海华东分公司");
        Department node4 = new Department("财务部");
        Department node5 = new Department("南京办事处");
        Department node6 = new Department("杭州办事处");
        // 构建树
        node1.add(node2);
        node1.add(node3);
        node1.add(node4);
        node3.add(node5);
        node3.add(node2);
        node3.add(node4);
        node3.add(node6);
        node5.add(node2);
        node5.add(node4);
        node6.add(node2);
        node6.add(node4);
        node1.print(0);
        // 构建责任链
        node5.setSuccessor(node3);
        node6.setSuccessor(node3);
        node3.setSuccessor(node1);
        // 设置加薪边界
        node5.setBound(0,1000);
        node6.setBound(0,1000);
        node3.setBound(1000,2000);
        node1.setBound(2000,3000);
        // 请求加薪
        System.out.println("**********************");
        node5.handlerRequest(500);
        System.out.println("**********************");
        node5.handlerRequest(1500);
        System.out.println("**********************");
        node5.handlerRequest(2500);
        System.out.println("**********************");
        node5.handlerRequest(3500);
    }
}

实验五:解释器模式 实验题目

利用解释器模式,打印并计算实现浮点数的四则运算

例如:3+(4*6-(7/2))=23.5

目录结构
G:.
│  Client.java
└─expression
    │  Context.java
    │  expression.java
    │  Variable.java
    └─impl
            Addexpression.java
            Bracket.java
            Divexpression.java
            Mulexpression.java
            Subexpression.java
实验代码

声明抽象类:

public abstract class expression {
    
    public abstract double interpreter(Context con);

    
    public abstract void display(Context con);
}

变量封装:

public class Variable extends expression {
    @Override
    public double interpreter(Context con) {
        return con.LookupValue(this);
    }

    @Override
    public void display(Context con) {
        System.out.print(con.LookupValue(this));
    }
}
public class Context {
    private Map valueMap = new HashMap<>();

    
    public void addValue(Variable x,double y){
        valueMap.put(x, y);
    }

    
    public double LookupValue(Variable x){
        return valueMap.get(x);
    }
}

具体实现的加减乘除括号 *** 作:

public class Addexpression extends expression{
    private expression left;
    private expression right;

    public Addexpression(expression left, expression right) {
        this.left = left;
        this.right = right;
    }

    
    @Override
    public double interpreter(Context con) {
        return left.interpreter(con)+right.interpreter(con);
    }

    @Override
    public void display(Context con) {
        left.display(con);
        System.out.print("+");
        right.display(con);
    }
}
public class Subexpression extends expression{
    private expression left;
    private expression right;

    public Subexpression(expression left, expression right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public double interpreter(Context con) {
        return left.interpreter(con)-right.interpreter(con);
    }

    @Override
    public void display(Context con) {
        left.display(con);
        System.out.print("-");
        right.display(con);
    }
}
public class Mulexpression extends expression {
    private expression left;
    private expression right;

    public Mulexpression(expression left, expression right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public double interpreter(Context con) {
        return left.interpreter(con)*right.interpreter(con);
    }

    @Override
    public void display(Context con) {
        left.display(con);
        System.out.print("*");
        right.display(con);
    }
}
public class Divexpression extends expression {
    private expression left;
    private expression right;

    public Divexpression(expression left, expression right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public double interpreter(Context con) {
        return (1.0*left.interpreter(con))/right.interpreter(con);
    }

    @Override
    public void display(Context con) {
        left.display(con);
        System.out.print("/");
        right.display(con);
    }
}
public class Bracket extends expression {
    private expression exp;

    public Bracket(expression exp) {
        this.exp = exp;
    }

    @Override
    public double interpreter(Context con) {
        return exp.interpreter(con);
    }

    @Override
    public void display(Context con) {
        System.out.print("(");
        exp.display(con);
        System.out.print(")");
    }
}

客户端测试:

public class Client {
    public static void main(String[] args) {
        expression exp;
        Context con = new Context();
        Variable a = new Variable();
        Variable b = new Variable();
        Variable c = new Variable();
        Variable d = new Variable();
        Variable e = new Variable();
        con.addValue(a,3);
        con.addValue(b,4);
        con.addValue(c,6);
        con.addValue(d,7);
        con.addValue(e,2);
        exp = new Addexpression(a,new Bracket(new Subexpression(new Mulexpression(b,c),new Divexpression(d,e))));
        exp.display(con);
        System.out.print("="+exp.interpreter(con));
    }
}

大作业 一 题目

综合利用抽象工厂模式和单件模式,模拟实现服装工厂生产衣服的过程,具体内容如下:

现有两种服装品牌的工厂A和B,品牌A和品牌B的工厂都可以生产夹克和裤子,利用抽象工厂模式实现生产各种品牌的夹克和裤子的代码(即打印“生产A品牌夹克”之类的句子即可),并且利用单件模式,将品牌A和品牌B的工厂实现为单件。

试完成以下工作:

(1)画出UML类图

(2)给出核心实现代码

项目目录结构
G:.
│  Client.java
├─bean
│  │  Jacket.java
│  │  Trouser.java
│  │
│  ├─jacket
│  │      JacketA.java
│  │      JacketB.java
│  └─trouser
│          TrouserA.java
│          TrouserB.java
└─factory
    │  AbstractFactory.java
    └─impl
            AFactory.java
            BFactory.java
实现代码

夹克和上衣接口及实现类:

public interface Jacket {
    void printJacket();
}
public interface Trouser {
    void printTrouser();
}
public class JacketA implements Jacket {
    @Override
    public void printJacket() {
        System.out.println("生产A牌夹克");
    }
}
public class JacketB implements Jacket {
    @Override
    public void printJacket() {
        System.out.println("生产B牌夹克");
    }
}
public class TrouserA implements Trouser {
    @Override
    public void printTrouser() {
        System.out.println("生产A牌上衣");
    }
}
public class TrouserB implements Trouser {
    @Override
    public void printTrouser() {
        System.out.println("生产B牌上衣");
    }
}

定义工厂:

public abstract class AbstractFactory {
    public abstract Jacket getJacket();
    public abstract Trouser getTrouser();
}
public class AFactory extends AbstractFactory {
    private static AFactory instanceA = new AFactory();

    public static AFactory getInstanceA(){
        return instanceA;
    }

    @Override
    public Jacket getJacket() {
        return new JacketA();
    }

    @Override
    public Trouser getTrouser() {
        return new TrouserA();
    }
}
public class BFactory extends AbstractFactory {
    private static BFactory instanceB = new BFactory();

    public static BFactory getInstanceB(){
        return instanceB;
    }

    @Override
    public Jacket getJacket() {
        return new JacketB();
    }

    @Override
    public Trouser getTrouser() {
        return new TrouserB();
    }
}

客户端测试:

public class Client {
    public static void main(String[] args) {
        AFactory instanceA = AFactory.getInstanceA();
        instanceA.getJacket().printJacket();
        instanceA.getTrouser().printTrouser();

        BFactory instanceB = BFactory.getInstanceB();
        instanceB.getJacket().printJacket();
        instanceB.getTrouser().printTrouser();
    }
}

UML图

二 题目

利用解释器模式,实现只含加减法及括号的代数表达式的打印及运算。例如对于代数表达式a+b-(c+3),当给a赋值3,b赋值4,c赋值5时,输出如下:

a+b-(c+3)
=3+4-(5+3)
=-1

其中变量名只能是‘a’,’b’,…,’z’,所有变量赋值以及常数都是0-9之间的整数。输出结果中第一行打印原始表达式,a+b-(c+3),即含有变量名;第二行将变量替换为所赋的值,即3+4-(5+3);第三行打印计算结果。

试完成以下工作:

(1)给出文法表达式

(2)画出UML类图

(3)给出核心实现代码

项目目录结构
G:.
│  Client.java
│  Context.java
│  expression.java
│  Variable.java
└─impl
        Addexpression.java
        Bracket.java
        Subexpression.java
实现代码

接口与变量类:

public abstract class expression {
    public abstract double interpreter(Context con);
    public abstract void display(Context con);
}
public class Context {
    private Map valueMap = new HashMap<>();
    public void addValue(Variable x,double y){
        valueMap.put(x,y);
    }
    public double lookupValue(Variable x){
        return valueMap.get(x);
    }
}
public class Variable extends expression {
    @Override
    public double interpreter(Context con) {
        return con.lookupValue(this);
    }
    @Override
    public void display(Context con) {
        System.out.print(con.lookupValue(this));
    }
}

实现的运算:

public class Addexpression extends expression {
    private expression left;
    private expression right;

    public Addexpression(expression left, expression right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public double interpreter(Context con) {
        return left.interpreter(con)+right.interpreter(con);
    }

    @Override
    public void display(Context con) {
        left.display(con);
        System.out.print("+");
        right.display(con);
    }
}
public class Subexpression extends expression {
    private expression left;
    private expression right;

    public Subexpression(expression left, expression right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public double interpreter(Context con) {
        return left.interpreter(con)-right.interpreter(con);
    }

    @Override
    public void display(Context con) {
        left.display(con);
        System.out.print("-");
        right.display(con);
    }
}
public class Bracket extends expression {
    private expression exp;

    public Bracket(expression exp) {
        this.exp = exp;
    }

    @Override
    public double interpreter(Context con) {
        return exp.interpreter(con);
    }

    @Override
    public void display(Context con) {
        System.out.print("(");
        exp.display(con);
        System.out.print(")");
    }
}

客户端测试:

public class Client {
    public static void main(String[] args) {
        expression exp;
        Context con = new Context();
        Variable a = new Variable();
        Variable b = new Variable();
        Variable c = new Variable();
        con.addValue(a,3);
        con.addValue(b,4);
        con.addValue(c,5);
        Variable d = new Variable();
        con.addValue(d,3);
        exp = new Subexpression(new Addexpression(a,b),new Bracket(new Addexpression(c,d)));
        System.out.print("a+b-(c+3)n=");
        exp.display(con);
        System.out.println("n="+exp.interpreter(con));
    }
}

UML图

三 题目

利用观察者模式和中介者模式,实现一个二元函数的函数计算器。该计算器含有两个数据类:

class A{
    int x;
}
class B{
    int y;
}

分别存储整型变量x和y。需要实现三个函数计算器类,分别计算f1(x,y)=x+y,f2(x,y)=x-y和f3(x)=2x。

要求:

(1)当且仅当类A和类B都发布通知时,3个函数计算器才相应地计算出3个新的值。

(2)类A、类B与三个函数计算器类尽可能解耦。

(3)可以动态地增加和减少函数计算器。

试完成以下工作:

(1)画出UML类图

(2)通过修改类A和类B,以及增加适当的类,实现其代码

项目目录结构
G:.
│  Client.java
├─data
│      A.java
│      AbstractData.java
│      B.java
├─mediator
│      AbstractMediator.java
│      ConcreteMediator.java
└─observer
        F1.java
        F2.java
        F3.java
        Observer.java
实现代码

数据类:

public abstract class AbstractData {
    protected AbstractMediator abstractMediator;
    public int num;

    public AbstractData(AbstractMediator abstractMediator) {
        this.abstractMediator = abstractMediator;
    }

    public abstract void send(int num);
}
public class A extends AbstractData {
    public A(AbstractMediator abstractMediator) {
        super(abstractMediator);
    }

    @Override
    public void send(int num) {
        abstractMediator.send(num,this);
    }
}
public class B extends AbstractData {
    public B(AbstractMediator abstractMediator) {
        super(abstractMediator);
    }

    @Override
    public void send(int num) {
        abstractMediator.send(num,this);
    }
}

中介者+被观察者:

这个中介者类兼有两种智能:

作为中介器作为被观察的对象

public abstract class AbstractMediator {
    // 作为中介器的接口
    public abstract void send(int num, AbstractData abstractData);

    // 被观察者
    private List observerList = new linkedList<>();

    public void attach(Observer observer){
        observerList.add(observer);
    }
    public void detach(Observer observer){
        observerList.remove(observer);
    }
    public void notifyObserver(){
        for (Observer o:observerList) {
            o.update();
        }
    }
}
public class ConcreteMediator extends AbstractMediator {
    private A a;
    private B b;

    @Override
    public void send(int num, AbstractData abstractData) {
        if (a == abstractData) {
            a.num = num;
        } else if (b == abstractData) {
            b.num = num;
        }
    }

    public void setA(A a) {
        this.a = a;
    }

    public void setB(B b) {
        this.b = b;
    }

    public A getA() {
        return a;
    }

    public B getB() {
        return b;
    }
}

观察者类:

public interface Observer {
    void update();
}
public class F1 implements Observer{
    private int result;
    private ConcreteMediator concreteMediator;

    public F1(ConcreteMediator concreteMediator) {
        this.concreteMediator = concreteMediator;
    }

    @Override
    public void update() {
        result = concreteMediator.getA().num+concreteMediator.getB().num;
        showResult();
    }

    public void showResult() {
        System.out.println("函数f1(x,y)=x+y计算结果="+result);
    }
}
public class F2 implements Observer {
    private int result;
    private ConcreteMediator concreteMediator;

    public F2(ConcreteMediator concreteMediator) {
        this.concreteMediator = concreteMediator;
    }
    @Override
    public void update() {
        result = concreteMediator.getA().num-concreteMediator.getB().num;
        showResult();
    }

    public void showResult() {
        System.out.println("函数f2(x,y)=x-y计算结果="+result);
    }
}
public class F3 implements Observer {
    private int result;
    private ConcreteMediator concreteMediator;

    public F3(ConcreteMediator concreteMediator) {
        this.concreteMediator = concreteMediator;
    }

    @Override
    public void update() {
        result = concreteMediator.getA().num*2;
        showResult();
    }

    public void showResult() {
        System.out.println("函数f3(x)=2x计算结果="+result);
    }
}
public class Client {
    public static void main(String[] args) {
        // mediator既做中介器,又做被观察的对象
        ConcreteMediator mediator = new ConcreteMediator();
        A a = new A(mediator);
        B b = new B(mediator);
        mediator.setA(a);
        mediator.setB(b);
        a.send(20);
        b.send(5);

        mediator.attach(new F1(mediator));
        mediator.attach(new F2(mediator));
        mediator.attach(new F3(mediator));
        mediator.notifyObserver();
        // 让对象a发布新的通知
        System.out.println("************新通知*************");
        a.send(-100);
        mediator.notifyObserver();
    }
}

UML图

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5717868.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存