适配器,组合模式

实验目的与任务

目的:熟悉UML的使用,熟悉适配器、组合模式。

任务:按照实验内容要求,完成使用适配器、组合模式实现实验功能。

预习内容

复习UML课程的内容,熟悉适配器、组合模式的使用。

实验内容及要求

  • 适配器模式:

1、现有一类Square中方法squ(float  l)用于计算正方形的面积,现在要求有类Circle用于计算圆的内接正方形的面积,请用适配器模式实现该面积的输出,要求复用Square,请绘制类图并编码实现。

  • 组合模式:

有如下场景:大学的结构为:大学-学院-系,请根据我校的情况实例化该结构,并且要求学院能够发信息给指定的系(例如:计算机科学与工程学院可以发送消息至软件工程系),请结合组合模式绘制类图并编码实现。

实验结果(可续页)

一:适配器模式

 

Target(目标抽象类):

Circle.java:

package target;

 

public interface Circle {

    public float inter_squ(float l);

    public float squ(float l);

}

 

Adapter(适配器类):

Adapter.java:

 

Adaptee(适配者类):

Square.java:

 

Main:

Main.java:

二:组合模式

Component(抽象构件):

univComponent.java:

 

Leaf(叶子构件):

Department.java:

 

Composite(容器构件):

College,java:

 

Univ.java:

package Composite;

import java.util.ArrayList;

import Component.univComponent;

import Composite.College;

public class Univ extends univComponent{

    private String name;

    private java.util.List<College> collegeList=new ArrayList<College>();

    public Univ(String name){

        this.name=name;

    }

    public void add(univComponent univComponent) {

        // TODO Auto-generated method stub

        collegeList.add((College)univComponent);

       

    }

    public java.util.List<College> getCollegeList(){

        return collegeList;

    }

    public void setCollegeList(java.util.List<College> collegeList){

        this.collegeList=collegeList;

    }

    @Override

    public void sendMessage(String msg,univComponent univComponent) {

        College college=(College)univComponent;

        if(collegeList.contains(univComponent)){

           System.out.println(this.name+"发送信息"+college.getName()+":"+msg+"");

 

        }

    }

    public void remove(univComponent univComponent){

        collegeList.remove(univComponent);

    }

    @Override

    public String getName() {

        // TODO Auto-generated method stub

        return name;

    }

    public void setName(String name){

        this.name=name;

    }

 

}

 

Main:

Main.java:

 

 

 

思考题:

  1. 如何区别类适配器和对象适配器?

类适配器需要通过创建自身创建出一个新的Adapter,对象适配器可以通过已有的Adapter对象来装换接口类适配器通过覆写来扩展specificRequest(),对象适配器是包含关系不能扩展类适配器因为是继承所以相对静态,对象适配器是包含,所以相对灵活

2、算术运算:1+2中1、2是运算量,+是运算符,另外1+(2*3)也是算术运算,但是包含了(2*3),本身也是算术运算,请结合组合模式给出该算术运算的类图。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

猜你喜欢

转载自blog.csdn.net/yszbrzdd/article/details/93521322