生成器模式的应用

实验旨在掌握生成器模式,通过实现EconHouseBuilder类设计经济型房屋,该房屋具有较小面积、较少卧室和卫生间,无花园和游泳池。在HouseBuyerGUI中添加了Economy_House选项,用户可以选择并配置房屋的详细参数,如面积、卧室和车库数量。实验总结强调了生成器模式在构建复杂对象时的优势,特别是在对象组件关联和构建顺序管理方面。
摘要由CSDN通过智能技术生成

【实验目的】

  1. 掌握生成器模式(builder)的特点
  2. 分析具体问题,使用生成器模式进行设计。
    【实验内容和要求】
    在例子2.5的设计中,添加一个经济型房屋生成器类,命名为EconHouseBuilder.注意经济型房屋的面积比较小,卧室、卫生间和车库的数量较少,且不包含花园和游泳池设计写出实现代码,具体要求见光盘的相应作业部分。
    【模式UML图】
    在这里插入图片描述
    在这里插入图片描述

【模式代码(JAVA语言实现)】需要添加代码的模块
1.HouseBuyerGUI.class类

package ccc;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class HouseBuyerGUI extends JPanel{
   private JScrollPane btnPane;
   private JScrollPane houseInfoPane;
   private JTextArea txtHouseInfo;
   private JSplitPane bigSplitPane;
   private JSplitPane upSplitPane;
   private JPanel downPanel;
   private JComboBox cmbHouseType;
   private JPanel buttonPanel;
   private JPanel houseOptPanel;
   private ButtonHandler bh;

   static final Dimension minimumSize = new Dimension(230, 200);
   public static final String SUBMIT= "Submit";
   public static final String EXIT = "Exit";
   //public static final String ECONOMY_HOUSE = "Economy House";
   public static final String NORMAL_HOUSE = "Normal House";
   public static final String LUXURY_HOUSE = "Luxury House";
   public static final String BLANK = "Choose House Type";
   public static final String ECONOMY_HOUSE = "Econnomy House";
   
   public HouseBuyerGUI(){
      super(new GridLayout(1,0));
	  txtHouseInfo=new JTextArea(6, 20);
	  txtHouseInfo.setFont(new Font("Arial", Font.BOLD, 14));
	  txtHouseInfo.setLineWrap(true);
      txtHouseInfo.setBackground(Color.pink);
      txtHouseInfo.setText("House Information");

      bh = new ButtonHandler();

      setupLowerPanel();
	  setupUpperLeftPanel();
      buildUpScrollGUI();
   }

   private void setupLowerPanel(){
      downPanel = new JPanel();
      downPanel.setBackground(Color.gray);
	  JButton btnSubmit = new JButton(HouseBuyerGUI.SUBMIT);
	  btnSubmit.setMnemonic(KeyEvent.VK_G);
	  JButton btnExit = new JButton(HouseBuyerGUI.EXIT);
	  btnExit.setMnemonic(KeyEvent.VK_X);
	  btnSubmit.addActionListener(bh);
	  btnExit.addActionListener(bh);

      downPanel.add(btnSubmit);
      downPanel.add(btnExit);
   }
   private void setupUpperLeftPanel(){
      cmbHouseType = new JComboBox();
      cmbHouseType.addItem(BLANK);

      cmbHouseType.addItem(NORMAL_HOUSE);
      cmbHouseType.addItem(LUXURY_HOUSE);
      cmbHouseType.addItem(ECONOMY_HOUSE);

      JLabel lblHouseType = new JLabel("House Type:");
      JLabel lblHouseOptions = new JLabel("Options:");
      cmbHouseType.addActionListener(bh);

      //For layout purposes, put the buttons in a separate panel
      buttonPanel = new JPanel();
      // houseOptPanel is an empty panel for holding a HouseGUI dynamically
      // houseOptPanel will be put on buttonPanel
      houseOptPanel = new JPanel();
      houseOptPanel.setPreferredSize(new Dimension(360, 180));

      //****************************************************
      GridBagLayout gridbag = new GridBagLayout();

      buttonPanel.setLayout(gridbag);
      GridBagConstraints gbc = new GridBagConstraints();

      buttonPanel.add(cmbHouseType);
      buttonPanel.add(houseOptPanel);

      gbc.insets.top = 5;
      gbc.insets.bottom = 5;
      gbc.insets.left = 5;
      gbc.insets.right = 5;

      gbc.anchor = GridBagConstraints.WEST;
      gbc.gridx = 0;
      gbc.gridy = 0;
      gridbag.setConstraints(cmbHouseType, gbc);
      gbc.gridx = 0;
      gbc.gridy = 1;
      gridbag.setConstraints(houseOptPanel, gbc);
   }

   public void showHouseInfo(String str){
      txtHouseInfo.setText(str);
   }
   public String getHouseType(){
      return (String) cmbHouseType.getSelectedItem();
   }
   public JComboBox getHouseTypeCombox(){
      return cmbHouseType;
   }
   public void displayNewGUI(JPanel panel){
      houseOptPanel.removeAll();
      houseOptPanel.add(panel);
      houseOptPanel.validate();
      validate();
   }
   private void buildUpScrollGUI(){
      btnPane = new JScrollPane(buttonPanel);
	  btnPane.setMinimumSize(minimumSize);
	  houseInfoPane = new JScrollPane(txtHouseInfo);

	  upSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
	  upSplitPane.setDividerLocation(390);
	  upSplitPane.setPreferredSize(new Dimension(600, 280));

	  upSplitPane.setLeftComponent(btnPane);
	  upSplitPane.setRightComponent(houseInfoPane);
	  bigSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upSplitPane, downPanel);
	  bigSplitPane.setDividerLocation(280);

	  add(bigSplitPane);
	  setSize(new Dimension(600, 300));
      setVisible(true);
  }

  private static void createAndShowGUI(){
     JFrame.setDefaultLookAndFeelDecorated(true);
     JFrame frame = new JFrame("Builder Pattern-House Sale Software");
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

     HouseBuyerGUI newContentPane = new HouseBuyerGUI();
     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();
		}
        });
  }
  class ButtonHandler implements ActionListener{
     HouseBuilder builder;

     public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals(EXIT)) {
           System.exit(1);
        }
        if (e.getActionCommand().equals(SUBMIT)) {
		   if(builder != null){
              //For displaying user's request
              String usrRequest = builder.getUserRequest();
              showHouseInfo(usrRequest);


		      Director director = new Director();

		      //decide which builder to use
		      director.setHouseBuilder(builder);

		      //For constructing the whole House object
		      director.constructWholeHouseObj();

		      //get a House object
		      House hsObj = director.getHouse();

		      //Show house object
		      int housePrice = hsObj.getHousePrice();
		      txtHouseInfo.append("\n House Price: "+housePrice);
	       }
        }
	    if (e.getSource() == getHouseTypeCombox()) {
           String selection = getHouseType();
           if ( (selection.equals("") == false) && (selection.equals(BLANK) == false)) {
              BuilderFactory factory = new BuilderFactory();

              //Get a concrete builder,eg., Object NormHouseBuilder
              //and add this component to the GUI
              builder = factory.getUIBuilder(selection);
              builder.addUIComponents();

              //Get and display the currently chosen Gui component
              JPanel UIObj = builder.getSearchUI();
              displayNewGUI(UIObj);
              buttonPanel.repaint();
           }
        }
     }
  }
}

class BuilderFactory{

	public HouseBuilder getUIBuilder(String str){
        HouseBuilder builder = null;

if(str.equals(HouseBuyerGUI.NORMAL_HOUSE)){
         builder = new NormHouseBuilder();
}
else if (str.equals(HouseBuyerGUI.LUXURY_HOUSE)){
         builder = new LuxHouseBuilder();
 
}else if (str.equals(HouseBuyerGUI.ECONOMY_HOUSE)){
         builder = new EconHouseBuilder();
  }
         return builder;
     }
}

2.EconHouseBuilder.class类:

package ccc;


```cpp
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EconHouseBuilder extends HouseBuilder{
   public static final String SMALL_AREA = "180 sq meters";
   public static final String BIG_AREA = "210 sq meters";
   public static final String LESS_BEDROOM = "2";
   public static final String MORE_BEDROOM = "3";
   public static final String LESS_BATHROOM = "1";
   public static final String MORE_BATHROOM = "2";
   public static final String SMALL_GARAGE = "1-car garage";
   public static final String BIG_GARAGE = "2-car garage";
   public static final String ECONOMY_TYPE = "Economy-type house";
   public EconHouseBuilder(){
	  area = null;
      bedroom = null;
      bathroom = null;
      garage = null;
      garden = null;
      swimmingPool = null;
   }
   public void addUIComponents(){
      houseGUI = new JPanel();
  	  houseGUI.setLayout(new GridLayout(4,3));
	  JLabel label1 = new JLabel("Area:");
	  JLabel label2 = new JLabel("Bed room number:");
	  JLabel label3 = new JLabel("Bathroom number:");
	  JLabel label4 = new JLabel("Garage type:");
       JRadioButton areaBtn1 = new JRadioButton(SMALL_AREA);
       JRadioButton areaBtn2 = new JRadioButton(BIG_AREA);
       JRadioButton bedroomBtn1 = new JRadioButton(LESS_BEDROOM);
       JRadioButton bedroomBtn2 = new JRadioButton(MORE_BEDROOM);
       JRadioButton bathroomBtn1 = new JRadioButton(LESS_BATHROOM);
       JRadioButton bathroomBtn2 = new JRadioButton(MORE_BATHROOM);
       JRadioButton garageBtn1 = new JRadioButton(SMALL_GARAGE);
       JRadioButton garageBtn2 = new JRadioButton(BIG_GARAGE);
       ButtonGroup areaGroup = new ButtonGroup();
       ButtonGroup bedroomGroup = new ButtonGroup();
       ButtonGroup bathroomGroup = new ButtonGroup();
       ButtonGroup garageGroup = new ButtonGroup();
       areaGroup.add(areaBtn1);
       areaGroup.add(areaBtn2);
       bedroomGroup.add(bedroomBtn1);
       bedroomGroup.add(bedroomBtn2);
       bathroomGroup.add(bathroomBtn1);
       bathroomGroup.add(bathroomBtn2);
       garageGroup.add(garageBtn1);
       garageGroup.add(garageBtn2);
       houseGUI.add(label1);
       houseGUI.add(areaBtn1);
       houseGUI.add(areaBtn2);
       houseGUI.add(label2);
       houseGUI.add(bedroomBtn1);
       houseGUI.add(bedroomBtn2);
       houseGUI.add(label3);
       houseGUI.add(bathroomBtn1);
       houseGUI.add(bathroomBtn2);
       houseGUI.add(label4);
       houseGUI.add(garageBtn1);
       houseGUI.add(garageBtn2);
       areaBtn1.addActionListener(new AreaListener());
       areaBtn2.addActionListener(new AreaListener());
       bedroomBtn1.addActionListener(new BedroomListener());
       bedroomBtn2.addActionListener(new BedroomListener());
       bathroomBtn1.addActionListener(new BathroomListener());
       bathroomBtn2.addActionListener(new BathroomListener());
       garageBtn1.addActionListener(new GarageListener());
       garageBtn2.addActionListener(new GarageListener());
	  //Add code here
  }
   /* Build up a whole object incrementally */
   public void buildType(){
 	 house.setType(ECONOMY_TYPE);
   }
   public void buildArea(){
       house.setArea(area);
 	 // Add code here
   }
   public void buildBedroom(){
       house.setBedroom(bedroom);
      // Add code here
   }
   public void buildBathroom(){
       house.setBathroom(bathroom);
 	 // Add code here
   }
   public void buildGarage(){
       house.setGarage(garage);
 	 // Add code here
   }
   public void buildGarden(){
       house.setGarden(garden);
 	 // Add code here
   }
   public void buildSwimmingpool(){
       house.setSwimmingPool(swimmingPool);
      // Add code here
   }
  //This method returns user chosen requests
  //as a string to be displayed on screen
  public String getUserRequest(){
	 String usrRequest = null;
	 if((area==null)||(bedroom==null)||(bathroom==null)||(garage==null)){
	    usrRequest = "Incomplete items";
	 }
	 else{
	    usrRequest = ECONOMY_TYPE
                     +"\nArea =" + area
                     +"\nBedroom number= " + bedroom
                     + "\nBathroom number = " + bathroom
                     + "\nGarage type = " + garage;
	 }
     return usrRequest;
  }
}// end class**

【运行截图】
在这里插入图片描述
在这里插入图片描述

【实验小结】
通过本次实验,学会了使用生成器方法模式。生成器方法模式的适用性如下:
须要建立的产品对象有复杂的内部结构时(这是基础,否则不须要使用分步构建算法来建立和组装产品的各个子部件部分)。
当建立复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。
须要建立的复杂对象内部的各个子部分有必定的关联性或者依赖性,这样在能够经过生成器来强迫生成必定的建立和组装顺序。
当构造过程必须容许被构造的对象有不一样的表示时。由于若是经过相同的构造过程只有一种内部表象时,就无所谓利用生成器模式呢,这时或许使用工厂方式模式更合适、方便些。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值