Java 生成器模式

2018-01-17 17:48 更新

Java設(shè)計(jì)模式 - 生成器模式


生成器模式用于使用簡(jiǎn)單對(duì)象創(chuàng)建復(fù)雜對(duì)象。它從小而簡(jiǎn)單的對(duì)象逐步創(chuàng)建更大的對(duì)象。

生成器模式是另一個(gè)創(chuàng)建模式。

例如,當(dāng)創(chuàng)建一個(gè)窗口作為我們應(yīng)用程序的主窗口時(shí),我們需要?jiǎng)?chuàng)建一個(gè)菜單,一個(gè)工具欄,然后添加菜單和工具欄。

對(duì)于我們要?jiǎng)?chuàng)建的每個(gè)窗口,我們需要?jiǎng)?chuàng)建一個(gè)空窗口,創(chuàng)建菜單,創(chuàng)建工具欄,將菜單和工具欄安裝到窗口。

我們可以使用構(gòu)建器模式來隱藏如何創(chuàng)建窗口的實(shí)現(xiàn)。

例子

class Menu {
}
class ToolBar {
}
class MainWindow {
  Menu menu;
  ToolBar toolBar;
  public Menu getMenu() {
    return menu;
  }
  public void setMenu(Menu menu) {
    this.menu = menu;
  }
  public ToolBar getToolBar() {
    return toolBar;
  }
  public void setToolBar(ToolBar toolBar) {
    this.toolBar = toolBar;
  }
}
class WindowBuilder{
  public static MainWindow createWindow(){
    MainWindow window = new MainWindow();
    Menu menu = new Menu();
    ToolBar toolBar = new ToolBar();
    window.setMenu(menu);
    window.setToolBar(toolBar);
    return window;
  }
}
public class Main {
  public static void main(String[] args) {
    MainWindow object = WindowBuilder.createWindow();

  }
}
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)