java创建型设计模式——生成器模式

  1. 模式理解:生成器设计模式说简单点就是在创建一个对象的同时一并创建对象的附属对象,比如创建一个3人的家庭对象,先创建家庭对象,同时家庭对象也包括父亲对象,母亲对象,再加上你自己,这都是一并创建的
  2. 运用场景:当对象存包含或有附属对象时可用
  3. 代码示例:来自(https://www.w3cschool.cn/java/java-builder-pattern.html

//先创建被包含的对象:

    public class Menu {

    }
    public class ToolBar {

    }

//再创建包含上述对象的对象:

public 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;
    }
   
}

//接着创建一个类进行实例化各对象:

public class WindowBuilder {

    public static MainWindow createMainWindow(){
        MainWindow mainWindow=new MainWindow();
        Menu menu=new Menu();
        ToolBar toolBar=new ToolBar();
        mainWindow.setMenu(menu);
        mainWindow.setToolBar(toolBar);
        return mainWindow;
    }
}

//最后写个测试用例:

public class Main {

    public static void main(String[] args) {
        WindowBuilder.createMainWindow();
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值