生成器模式(Builder Pattern)将一个复杂对象的构建与它的表示分离,使同样的构建过程可以创建不同的表示。
Builder模式是另一种创建模式。
例如,创建一个窗口,我们的应用程序的主窗口的时候,我们需要创建一个菜单,工具栏,然后添加菜单和工具栏。
对于我们要创建的每个窗口,我们需要创建一个空的窗口,创建菜单,创建一个工具栏,安装菜单和工具栏的窗口。
我们可以用生成器模式来隐藏如何创建一个窗口的实现。
class Menu {/*ww w. ja va2 s. co m*/
}
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 = WindowBuilder.createWindow();
}
}
继续阅读与本文标签相同的文章
下一篇 :
图解优秀软件设计人员的8个习惯
-
城市数字化后,新一代内生安全系统可全方位保护
2026-05-14栏目: 教程
-
谷歌也来“唱衰”5G,5G手机只会徒增功耗?为何这么说?
2026-05-14栏目: 教程
-
量子信息和量子技术白皮书合肥宣言在中科大发布
2026-05-14栏目: 教程
-
微信悄悄更新一新功能,来看看!
2026-05-14栏目: 教程
-
打破三大运营商垄断,第四大运营商终于来了!
2026-05-14栏目: 教程
