软件设计与体系结构 实验二 经典软件体系结构风格(二)

简介: 软件设计与体系结构 实验二 经典软件体系结构风格(二)

@[TOC](目录

写在前面

正确与否我不能确定,我自己写的,还有摆烂的,直接修改的参数名。

一、思考题1

从理论上讲,基于事件的隐式调用软件体系结构组件是什么?连接件是什么?特点是什么?上述实验1程序中具体的组件是什么?连接件是什么?

基于事件的隐式调用风格的基本组件是对象和过程,并分类为以下更小的组件:过程和函数,充当事件源或事件处理器的角色、事件。连接件是事件-过程绑定。组件可以声明一个或多个事件,或者向系统注册,来表明它希望响应一个或多个事件。当某些事件被发布(触发)时,向其注册的过程被隐式调用,调用的次序是不确定的。隐式调用风格的主要特点是事件的触发者并不知道哪些组件会被这些事件影响,这样不能假定组件的处理顺序,甚至不知道哪些过程会被调用,因此,许多隐式调用的系统也包含显式调用作为组件的补充形式。
程序中,组件有注册方法addActionListener()、发生的时间ActionEvent,还有事件源btn、监听器this(窗体对象本身,是下了Actionlistener接口的类的对象)。连接件如下,btn.addActionListener(this):将事件源按钮对象注册到监听器(this,窗体对象本身implements
Actionlistener)。系统定义对事件的处理方法,发生的时间为参数public void
actionPerformed(ActionEvent
e)。单击btn,触发ActionEvet事件,时间管理器(实现了ActionListener接口的类,本程序为窗体对象本身this)会根据发生的ActionEvent事件,自动调用actionPerformed()方法,执行方法体中的语句。

二、思考题2

从理论上讲,层次软件体系结构组件是什么?连接件是什么?特点是什么?上述实验3程序中具体的组件是什么?连接件是什么?

层次结构的基本组件是各层次及其内部包含的组件,连接件是层次间的交互协议。特点是在层次风格的系统中,内部的层只对相邻的层可见;交互只在相邻的层次间发生,同时这些交互按照一定协议进行。某些特殊化的层次风格体系结构允许非相邻层次间的直接通信,这往往出于效率方面的原因而作出的改变。
具体的组件包括:第一层的TestingGUI类,第二层的Testcase接口、TestcaseBubble类、TestcaseHeap类、TestcaseInscrtion类、ResultVerification类;第三层的BubbleSort类、HeapSort类、InsertSort类、SortAlgorithm接口。连接件如下:在第一层TestingGUI类中声明了第二层TestCaseBubble类的对象、TestcaseHeap类的对象和TestcaseInsertion的对象,并调用它们的execute()方法,第二层的各类的execute()方法将一个数组结果返回给第一层。第二层的TestcaseBubble类中声明了第三层的BubbleSort类的对象,并调用该类中的sort方法;第三层的BubbleSort类的sort()方法将对数组的排序结果返回给第二层。TestCase类和TestcaseInsertion类类似。

三、思考题3

编写一个基于事件的隐式调用软件体系结构的程序(功能自定),并说明程序中的组件是什么?连接件是什么?

package com.you;
import java.awt.*;
import java.awt.event.*;   //引入java.awt.event包处理事件
class BtnLabelAction extends Frame implements KeyListener{
    //声明窗口类(BtnLabelAction)并实现动作事件接口(ActionListener)
    Label prompt;
    Label view;
    void CreateWindow(){  //自定义方法
        setTitle("MyButton");
        prompt = new Label("你好");    //创建标签对象
        view = new Label("按下键盘的任意按键试试");    //创建按钮对象

        setLayout(new FlowLayout());    //布局设计,用于安排按钮、标签的位置
        add(prompt);                //将标签放入容器
        add(view);
        this.setFocusable(true);//获得焦点事件
        this.addKeyListener(this);
        setSize(300,100);
        setVisible(true);
    }
    public void actionPerformed(){//接口ActionListener的事件处理方法

            if(prompt.getText()=="你好")
                prompt.setText("再见");
            else
                prompt.setText("你好");
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("按下的键为"+e.getKeyChar());
        actionPerformed();
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
}
public class BtnTest{
    public static void main (String args[]){
        BtnLabelAction bla=new BtnLabelAction();
        bla.CreateWindow();
    }
}
程序中,组件有注册方法addKeyListener()、发生的时间keyEvent,事件源键盘事件,监听器this。连接件如下,btn.addActionListener(this):将键盘事件注册到监听器(this。系统定义对事件的处理方法,发生的时间为参数public
void keypress(keyEvent
e)。按下任意键,触发keypress事件,时间管理器会根据发生的presskey事件,自动调用actionPerformed()方法,执行方法体中的语句。

四、思考题4

编写一个层次软件体系结构的程序(功能自定),并说明程序中的组件是什么?连接件是什么?

批处理风格基本组件是独立的应用程序;连接件是某种类型的媒质。
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import com.sun.java.swing.plaf.windows.*;
public class MyGUI extends JPanel{
   private JTextArea txtTestInfo, txtMyCase;
   private JLabel lblMyCases;
   private JPanel buttonPanel;
   private JComboBox cmbMyCases;

   private static final String CASE_BUBBLE= "TC1-Test Bubble Sort";
   private static final String CASE_HEAP= "TC2-Test Heap Sort";
   private static final String CASE_INSERTION= "TC3-Test Insertion Sort";
   private static final String EXECUTE = "Execute";
   private static final String EXIT = "Exit";

   public MyGUI(){
      txtTestInfo=new JTextArea("Test output from source shown here\n", 6, 20);
      txtTestInfo.setLineWrap(true);
      txtMyCase = new JTextArea("MyCase info and test validation shown here\n", 4, 15);
      txtMyCase.setLineWrap(true);
      buildUpScrollGUI();
   }
   private void buildUpScrollGUI(){
      setUpButtonPanel();
      JScrollPane btnPane = new JScrollPane(buttonPanel);
      JScrollPane textPane = new JScrollPane(txtMyCase);
      textPane.setMinimumSize(new Dimension(250, 150));
      JScrollPane testDataPane = new JScrollPane(txtTestInfo);

      JSplitPane upSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
      upSplitPane.setLeftComponent(btnPane);
      upSplitPane.setRightComponent(testDataPane);
      JScrollPane downPane = new JScrollPane(textPane);

      Dimension minimumSize = new Dimension(130, 100);
      btnPane.setMinimumSize(minimumSize);
      textPane.setMinimumSize(new Dimension(100, 100));
      upSplitPane.setDividerLocation(270);
      upSplitPane.setPreferredSize(new Dimension(500, 300));

      JSplitPane bigSplitPane=new JSplitPane(JSplitPane.VERTICAL_SPLIT, upSplitPane, downPane);
      bigSplitPane.setDividerLocation(190);

      add(bigSplitPane);
      setSize(new Dimension(500, 400));
      setVisible(true);
  }

  private void setUpButtonPanel(){
      lblMyCases = new JLabel("Test Cases:");
      cmbMyCases = new JComboBox();
      cmbMyCases.addItem(CASE_BUBBLE);
      cmbMyCases.addItem(CASE_HEAP);
      cmbMyCases.addItem(CASE_INSERTION);

     //Create the open button
     JButton executeBtn = new JButton(EXECUTE);
     executeBtn.setMnemonic(KeyEvent.VK_S);
     JButton exitButton = new JButton(EXIT);
     exitButton.setMnemonic(KeyEvent.VK_X);

     BtnListener objButtonHandler = new BtnListener();
     // add action Listener
     executeBtn.addActionListener(objButtonHandler);
     exitButton.addActionListener(objButtonHandler);
     buttonPanel = new JPanel();

     GridBagLayout gridbag = new GridBagLayout();
     buttonPanel.setLayout(gridbag);
     GridBagConstraints gbc = new GridBagConstraints();
     buttonPanel.add(lblMyCases);
     buttonPanel.add(cmbMyCases);
     buttonPanel.add(executeBtn);
     buttonPanel.add(exitButton);
     gbc.insets.top = 5;
     gbc.insets.bottom = 5;
     gbc.insets.left = 5;
     gbc.insets.right = 5;

     gbc.anchor = GridBagConstraints.EAST;
     gbc.gridx = 0;
     gbc.gridy = 0;
     gridbag.setConstraints(lblMyCases, gbc);
     gbc.anchor = GridBagConstraints.WEST;
     gbc.gridx = 1;
     gbc.gridy = 0;
     gridbag.setConstraints(cmbMyCases, gbc);
     gbc.anchor = GridBagConstraints.EAST;
     gbc.insets.left = 2;
     gbc.insets.right = 2;
     gbc.insets.top = 25;
     gbc.anchor = GridBagConstraints.EAST;
     gbc.gridx = 0;
     gbc.gridy = 7;
     gridbag.setConstraints(executeBtn, gbc);
     gbc.anchor = GridBagConstraints.WEST;
     gbc.gridx = 1;
     gbc.gridy = 7;
     gridbag.setConstraints(exitButton, gbc);
  }
  public void showTestInfo(int[] str ){
      txtTestInfo.setText("");
      for(int n=0; n< str.length; n++)
            txtTestInfo.append(""+str[n]+" ");
  }
  public void showErrors(String err){
     txtMyCase.append(err+"\n");
  }
  public String getSelectedMyCase() {
          return (String) cmbMyCases.getSelectedItem();
  }

 class BtnListener implements ActionListener{
    private MyCase test;
    private String selectedMyCase;

    public void actionPerformed(ActionEvent e){
      String searchResult = null;
      int[] output=null;

      if (e.getActionCommand().equals(EXIT)){
         System.exit(1);
      }
      if (e.getActionCommand().equals(EXECUTE)){
                 selectedMyCase = getSelectedMyCase();
                 if(selectedMyCase.equals(CASE_BUBBLE))
                       test = new MyCaseMaoPao();
                 else if(selectedMyCase.equals(CASE_HEAP))
                       test = new MyCaseHaXi();
                 else if(selectedMyCase.equals(CASE_INSERTION))
                       test = new MyCaseInsertion();
                 output = test.execute(3000);
                 showTestInfo(output);
         }
          showErrors(selectedMyCase);
          boolean result = ResultVerification.isResultCorrect(output );
          showErrors("No Error found = " +result);
          long timeTaken = test.getTimeTaken();
          showErrors("Testing Time takes = " + timeTaken+"\n");
   }
 } // End of class BtnListener

 private static void createAndShowGUI(){
     JFrame.setDefaultLookAndFeelDecorated(true);
     JFrame frame = new JFrame("Layered Architecture- Software Testing");
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     MyGUI newContentPane = new MyGUI();
     newContentPane.setOpaque(true);
     frame.setContentPane(newContentPane);
     frame.pack();
     frame.setVisible(true);
  }
  static public void main(String argv[]) {
     javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
           createAndShowGUI();
        }
        });
  }
}

public class ResultVerification{
     static boolean flag = true;

     public static boolean isResultCorrect(int[] arr){
         for(int k=0; k<arr.length-1; k++){
             if(arr[k] > arr[k+1]){
                 flag=false;
                 System.out.println("error  "+ k);
                 //break;
             }
         }
         return flag;
      }
}

第二层为测试案例层,包括软件测试工程师所编写的测试案例
public interface MyCase{
     public  abstract  int[] execute(int len);
     public  abstract  long getTimeTaken();
}

class Context {
    SortAlgorithm alg;

    // Constructor
    public Context(SortAlgorithm alg) {
        this.alg = alg;
    }

    public int[] sortIntArray(int[] a) {
        return this.alg.sort(a);
    }
}

import java.util.Random;
public class IntegerArrGenerator{
    public static int[] generateInput(int len){
         int[] input= new int[len];
         Random r = new Random();
         for(int m=0; m< len; m++){
             input[m] = r.nextInt(len);
         }

         return input;
    }
}

import java.util.*;
public class MyCaseMaoPao implements MyCase{
     private long startTime;
     private long timeTaken=0;

     public int[] execute(int len) {
          startTime = System.currentTimeMillis();

          int[] input = IntegerArrGenerator.generateInput(len);

           SortAlgorithm sa = new MaoPao();
           Context context = new Context(sa);
           int[] intArray = context.sortIntArray(input);

          timeTaken = System.currentTimeMillis() - startTime;
           return intArray;
    }

    public long getTimeTaken(){
          return     timeTaken;
    }
}

import java.util.*;
public class MyCaseHaXi implements MyCase{
     //static long time;
     private long startTime;
     private long timeTaken=0;

     public int[] execute(int len){
        startTime = System.currentTimeMillis();
        int[] input = IntegerArrGenerator.generateInput(len);

        SortAlgorithm sa = new HaXi();
        Context context = new Context(sa);
        int[] intArray = context.sortIntArray(input);
        timeTaken = System.currentTimeMillis()-startTime;

        return intArray;
    }
    public long getTimeTaken(){
              return     timeTaken;
    }
}

import java.util.*;
public class MyCaseInsertion implements MyCase{
     private long startTime;
     private long timeTaken=0;

     public  int[] execute(int len){
            startTime = System.currentTimeMillis();

             int[] input = IntegerArrGenerator.generateInput(len);
             SortAlgorithm sa = new ChaRu();
             Context context = new Context(sa);
             int[] intArray = context.sortIntArray(input);

             timeTaken = System.currentTimeMillis()-startTime;
             return intArray;
    }
    public long getTimeTaken(){
              return     timeTaken;
    }
}

第三层为被测试软件层(排序算法)
public interface SortAlgorithm {
     int[] sort(int[] nums);
}

public class MaoPao implements SortAlgorithm {
   public int[] sort(int[] nums){
      for(int i = nums.length; --i >= 0;)
         for(int j = 0; j < i; j++){
            if(nums[j] > nums[j + 1]){

               //exchange nums[j+1] with nums[j]
               int T = nums[j];
               nums[j] = nums[j + 1];
               nums[j + 1] = T;
            }
         }
      return nums;
   }
}

public class HaXi implements SortAlgorithm{
     public int[] sort(int nums[ ]) {
          for(int i=nums.length; i>1; i--){
               buildBinaryHeapTree(nums, i - 1);
               swapLeadingNodeWithLastNode(nums, i - 1);
          }
          return nums;
     }

     public void buildBinaryHeapTree(int array[], int arrayBound){
           int leftChild, rightChild, biggerChild, temp;
           int root = (arrayBound-1)/2;

           // Find the bigger child index
           for(int i=root; i>=0; i--) {
                 leftChild = (2*i)+1;
                 rightChild = (2*i)+2;

                 if((leftChild <= arrayBound) && (rightChild <= arrayBound)){
                    if(array[rightChild] >= array[leftChild])
                        biggerChild = rightChild;
                    else
                       biggerChild = leftChild;
                 }
                else{
                    if(rightChild > arrayBound)
                       biggerChild = leftChild;
                   else
                      biggerChild = rightChild;
                }

               //swap the integer contained in the bigger child index
               //with that in the current parent node
               if(array[i] < array[biggerChild]){
                   temp = array[i];
                  array[i] = array[biggerChild];
                  array[biggerChild] = temp;
               }
          }
           return;
    }

    public static void swapLeadingNodeWithLastNode(int array[], int arrayBound){
          int  temp;
          temp = array[0];
         array[0] = array[arrayBound];
         array[arrayBound] = temp;
          return;
    }
}

public class ChaRu implements SortAlgorithm {
    public int[] sort(int[] nums){
       for (int i = 1; i < nums.length; i++){
          int j = i;
          int numToBeInserted = nums[i];

          while ((j > 0) && (nums[j-1] > numToBeInserted) ) {
             nums[j] = nums[j-1];
             j--;
          }
          nums[j] = numToBeInserted;
       }
       return nums;
   }
}
具体的组件包括:第一层的MyGUI类,第二层的MyCase接口、MyCaseMaoPao类、MyCaseHaXi类、MyCaseChaRu类、ResultVerification类;第三层的MaoPao类、HaXi类、ChaRu类、SortAlgorithm接口。连接件如下:在第一层MyGUI类中声明了第二层TestCaseBubble类的对象、MyCaseHaXi类的对象和MyCaseInsertion的对象,并调用它们的execute()方法,第二层的各类的execute()方法将一个数组结果返回给第一层。第二层的MyCaseMaoPao类中声明了第三层的MaoPao类的对象,并调用该类中的sort方法;第三层的MaoPao类的sort()方法将对数组的排序结果返回给第二层。TestCase类和MyCaseInsertion类类似。

五、思考题5

从理论上讲,批处理软件体系结构组件是什么?连接件是什么?编写一个批处理软件体系结构的程序(功能自定),并说明程序中的组件是什么?连接件是什么?

package com.you;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Sender {
    public static void main(String[] args) {
        char ch;
        File MyPath = new File("src\\main\\resources\\static");
        if(!MyPath.exists())
        {
            MyPath.mkdir();
            File MyFile = new File(MyPath,"Data.dat");
            try{
                FileOutputStream fout = new FileOutputStream(MyFile);
                System.out.println("Input a string");
                while((ch=(char)System.in.read())!='#')
                {
                    fout.write(ch);

                }
                fout.close();
            }catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
package com.you;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Receiver {
    public static void main(String[] args) {
        int chi;
        File MyPath = new File("src\\main\\resources\\static");
        File MyFile = new File(MyPath,"Data.dat");
        try {
            FileInputStream fin = new FileInputStream(MyFile);
            while((chi = fin.read())!=-1)
            {
                System.out.println((char)chi);
            }
            fin.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

    }
}
Data.dat
“作业太多了,少布置点,要不然摆烂了#“
组件是Sender程序和Receiver程序!

六、思考题6

编写一个包含3种以上体系结构风格的异构经典软件体系结构的程序(功能自定),并说明程序中用到哪些体系结构?每个体系结构中的组件是什么?连接件是什么?

Sender.class
package com.you;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Sender {
    public static void main(String[] args) {

        File MyPath = new File("src\\main\\resources\\static");
        if(!MyPath.exists())
        {
            MyPath.mkdir();
            wirteFlie(MyPath);

        }
    }

    private static void wirteFlie(File MyPath) {
        char ch;
        File MyFile = new File(MyPath,"Data.dat");
        try{
            FileOutputStream fout = new FileOutputStream(MyFile);
            System.out.println("Input a string");
            while((ch=(char)System.in.read())!='#')
            {
                fout.write(ch);

            }
            fout.close();
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}
Recieve.java
package com.you;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Receiver {
    public static void main(String[] args) {

        File MyPath = new File("src\\main\\resources\\static");
        readTool readTool = new readTool();
        readTool.read(MyPath);

    }
}
class readTool{
    public void read(File MyPath)
    {
        int chi;
        File MyFile = new File(MyPath,"Data.dat");
        try {
            FileInputStream fin = new FileInputStream(MyFile);
            while((chi = fin.read())!=-1)
            {
                System.out.println((char)chi);
            }
            fin.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}
Data.dat
“作业太多了,以后少布置点,要不然不写#”
用到了面向对象风格、主程序-子程序风格,批处理风格。批处理风格组件是Sender程序和Receiver程序,连接件是data.dat。面向对象风格组件是Receiver、ReadTool以及ReadTool的对象readTool。连接件如下,在Receiver类中创建ReadTool的对象readTool,在Render类中调用readTool的read方法。主程序-子程序风格组件是main方法和wirteFlie方法,连接件是调用-返回机制。
相关文章
|
19天前
|
缓存 编译器
软件体系结构 - 指令集架构
软件体系结构 - 指令集架构
24 0
|
19天前
|
前端开发 Java 数据库
软件体系结构 - 软件构件
软件体系结构 - 软件构件
18 0
|
2月前
|
存储 编解码 并行计算
【软件设计师备考 专题 】计算机系统的组成、体系结构分类及特性
【软件设计师备考 专题 】计算机系统的组成、体系结构分类及特性
60 0
|
6天前
|
XML 存储 JSON
软件体系结构 - 架构风格(9)基于规则的系统架构风格
【4月更文挑战第21天】软件体系结构 - 架构风格(9)基于规则的系统架构风格
12 0
|
15天前
|
消息中间件 编解码 前端开发
软件体系结构 - 软件架构风格
【4月更文挑战第13天】软件体系结构 - 软件架构风格
10 0
|
2月前
|
设计模式 存储 前端开发
【软件设计师备考 专题 】面向对象设计方法:体系结构、类的设计和用户接口设计
【软件设计师备考 专题 】面向对象设计方法:体系结构、类的设计和用户接口设计
61 0
|
存储 程序员 虚拟化
软件设计体系 实验一 经典软件体系结构风格
软件设计体系 实验一 经典软件体系结构风格