zoukankan      html  css  js  c++  java
  • 构造者模式

    你是否打过以下代码:

    public class Animal{
    private String name;
    private String breed;
    private String gender;
    private int weight;

    public Animal(String name, String breed) {
    this.name = name;
    this.breed = breed;
    }


    public Animal(String name, String breed,String gender,int weight) {
    this.name = name;
    this.breed = breed;
    this.gender=gender;
    this.weight=weight;
    }

    }



    上述代码,导致了在构造过程中JavaBean可能处于不一致的状态,也就是说实例化对象本该是一气呵成,但现在却分割成了两大步,这会导致它线程不安全,进一步引发不可预知的后果。
    Effective+Java作者joshua bloch推荐利用"Builder"模式(构造者模式),其核心就是不直接生成想要的对象,而是让客户端利用所有必要的参数调用构造器(或者静态工厂),
    得到一个builder对象,再调用类似setter的方法设置相关可选参数。

    代码如下:

    public class Animal{
    private String name;
    private String breed;
    private String gender;
    private int weight;


    public static class Builder {
    private String name;
    private String breed;
    private String gender;
    private int weight;


    public Builder(String name, int weight){
    this.name=name;
    this.weight=weight; }

    public Builder gender(String gender){
    this.gender=gender;
    return this; }

    public Builder breed(String breed){
    this.breed=breed;
    return this; }

    public Animal build(){
    return new Animal(this); }

    }

    private Animal(Builder builder){
    this.name=builder.name;
    this.breed=builder.breed;
    this.gender=builder.gender;
    this.weight=builder.weight; }

    }

     调用:
    Animal animal=new Animal.Builder("Tom",10).breed("Cat").build();

     

     

  • 相关阅读:
    K210识别水果模型
    一键开关机短路
    Arudino IDE添加STM32官方管理器stm32duino / Arduino_Core_STM32
    ESP32 Ble
    Blynk软件配置及Mixly编程教程
    Laravel安装及配置,完成基础的demo
    electron下载/打包慢?解决办法.....
    ESP32+PHP+MYSQL 搭建自己的物联网平台Demo
    PCA9536读写测试之MicroPython
    MSF实验2
  • 原文地址:https://www.cnblogs.com/neowu/p/10742355.html
Copyright © 2011-2022 走看看