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

     

     

  • 相关阅读:
    文艺青年、普通青年、2b青年到底是什么意思?
    CMake快速入门教程:实战
    shell脚本中变量$$、$0等的含义
    工作上的C/C++相关
    C/C++的一些备忘
    shell基础二十篇 一些笔记
    C++中this指针的用法详解
    【C++11】新特性——auto的使用
    一个很不错的bash脚本编写教程
    容器
  • 原文地址:https://www.cnblogs.com/neowu/p/10742355.html
Copyright © 2011-2022 走看看