java builder pattern_Java Design Patterns – Creational Design Pattern – Builder Pattern

本文介绍Builder模式在创建复杂应用窗口时的应用,如创建包含菜单和工具栏的主窗口,通过逐步构造隐藏实现细节。通过WindowBuilder类简化了窗口的实例化过程。

Preface

Builder pattern is used to create a complex object using simple objects. It creates the bigger object step by step from small and simple object.

Builder pattern is another creational pattern.

For example, when creating a window as our application's main window, we need to create a menu, a toolbar and then add the menu and toolbar.

For each window we are going to create, we need to create an empty window, create a menu, create a toolbar, install the menu and toolbar to the window.

We can use the builder pattern to hide the implementation of how to create a window.

Example

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值