java 生成器 设计模式_Java中的生成器设计模式

java 生成器 设计模式

Today we will look into Builder pattern in java. Builder design pattern is a creational design pattern like Factory Pattern and Abstract Factory Pattern.

今天,我们将研究Java中的Builder模式。 生成器设计模式是一种创新设计模式,工厂模式抽象工厂模式

生成器设计模式 (Builder Design Pattern)

Builder pattern was introduced to solve some of the problems with Factory and Abstract Factory design patterns when the Object contains a lot of attributes.

当对象包含很多属性时,引入了构建器模式来解决Factory和Abstract Factory设计模式的一些问题。

There are three major issues with Factory and Abstract Factory design patterns when the Object contains a lot of attributes.

当对象包含很多属性时,工厂设计模式和抽象工厂设计模式存在三个主要问题。

  1. Too Many arguments to pass from client program to the Factory class that can be error prone because most of the time, the type of arguments are same and from client side its hard to maintain the order of the argument.

    从客户端程序传递到Factory类的参数过多,这很容易出错,因为在大多数情况下,参数的类型是相同的,并且从客户端很难保持参数的顺序。
  2. Some of the parameters might be optional but in Factory pattern, we are forced to send all the parameters and optional parameters need to send as NULL.

    一些参数可能是可选的,但是在出厂模式下,我们被迫发送所有参数,而可选参数需要以NULL的形式发送。
  3. If the object is heavy and its creation is complex, then all that complexity will be part of Factory classes that is confusing.

    如果对象很重且其创建很复杂,那么所有这些复杂性将成为混淆的Factory类的一部分。

We can solve the issues with large number of parameters by providing a constructor with required parameters and then different setter methods to set the optional parameters. The problem with this approach is that the Object state will be inconsistent until unless all the attributes are set explicitly.

通过为构造函数提供必需的参数,然后提供不同的setter方法来设置可选参数,我们可以解决大量参数的问题。 这种方法的问题在于,除非明确设置所有属性,否则对象状态将一直不一致

Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object.

Builder模式通过提供一种逐步构建对象并提供一种将实际返回最终Object的方法的方式,解决了具有大量可选参数和状态不一致的问题。

Java中的生成器设计模式 (Builder Design Pattern in Java)

Let’s see how we can implement builder design pattern in java.

让我们看看如何在Java中实现构建器设计模式。

  1. First of all you need to create a static nested class and then copy all the arguments from the outer class to the Builder class. We should follow the naming convention and if the class name is Computer then builder class should be named as ComputerBuilder.

    首先,您需要创建一个静态嵌套类 ,然后将所有参数从外部类复制到Builder类。 我们应该遵循命名约定,如果类名称为Computer则构建器类应命名为ComputerBuilder
  2. Java Builder class should have a public constructor with all the required attributes as parameters.

    Java Builder类应具有一个公共构造函数,其中带有所有必需的属性作为参数。
  3. Java Builder class should have methods to set the optional parameters and it should return the same Builder object after setting the optional attribute.

    Java Builder类应具有设置可选参数的方法,并且应在设置可选属性后返回相同的Builder对象。
  4. The final step is to provide a build() method in the builder class that will return the Object needed by client program. For this we need to have a private constructor in the Class with Builder class as argument.

    最后一步是在构建器类中提供build()方法,该方法将返回客户端程序所需的Object。 为此,我们需要在Class中有一个带有Builder类作为参数的私有构造函数。

Here is the sample builder pattern example code where we have a Computer class and ComputerBuilder class to build it.

这是示例构建器模式示例代码,其中有一个Computer类和ComputerBuilder类来构建它。

package com.journaldev.design.builder;

public class Computer {
	
	//required parameters
	private String HDD;
	private String RAM;
	
	//optional parameters
	private boolean isGraphicsCardEnabled;
	private boolean isBluetoothEnabled;
	

	public String getHDD() {
		return HDD;
	}

	public String getRAM() {
		return RAM;
	}

	public boolean isGraphicsCardEnabled() {
		return isGraphicsCardEnabled;
	}

	public boolean isBluetoothEnabled() {
		return isBluetoothEnabled;
	}
	
	private Computer(ComputerBuilder builder) {
		this.HDD=builder.HDD;
		this.RAM=builder.RAM;
		this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled;
		this.isBluetoothEnabled=builder.isBluetoothEnabled;
	}
	
	//Builder Class
	public static class ComputerBuilder{

		// required parameters
		private String HDD;
		private String RAM;

		// optional parameters
		private boolean isGraphicsCardEnabled;
		private boolean isBluetoothEnabled;
		
		public ComputerBuilder(String hdd, String ram){
			this.HDD=hdd;
			this.RAM=ram;
		}

		public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled) {
			this.isGraphicsCardEnabled = isGraphicsCardEnabled;
			return this;
		}

		public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) {
			this.isBluetoothEnabled = isBluetoothEnabled;
			return this;
		}
		
		public Computer build(){
			return new Computer(this);
		}

	}

}

Notice that Computer class has only getter methods and no public constructor. So the only way to get a Computer object is through the ComputerBuilder class.

请注意,Computer类仅具有getter方法,而没有公共构造函数。 因此,获取Computer对象的唯一方法是通过ComputerBuilder类。

Here is a builder pattern example test program showing how to use Builder class to get the object.

这是一个构建器模式示例测试程序,显示了如何使用Builder类来获取对象。

package com.journaldev.design.test;

import com.journaldev.design.builder.Computer;

public class TestBuilderPattern {

	public static void main(String[] args) {
		//Using builder to get the object in a single line of code and 
                //without any inconsistent state or arguments management issues		
		Computer comp = new Computer.ComputerBuilder(
				"500 GB", "2 GB").setBluetoothEnabled(true)
				.setGraphicsCardEnabled(true).build();
	}

}

生成器设计模式视频教程 (Builder Design Pattern Video Tutorial)

Recently I uploaded a YouTube video for Builder Design Pattern. I have also explained why I think the builder pattern defined on WikiPedia using Director classes is not a very good Object Oriented approach, and how we can achieve the same level of abstraction using different approach and with one class.

最近,我上传了一个关于Builder设计模式的YouTube视频。 我还解释了为什么我认为使用Director类WikiPedia上定义的构建器模式不是一种非常好的面向对象的方法,以及我们如何使用不同的方法和一个类来实现相同的抽象级别。

Note that this is my point of view, I feel design patterns are to guide us, but ultimately we have to decide if it’s really beneficial to implement it in our project or not. I am a firm believer of KISS principle.

请注意,这是我的观点,我认为设计模式可以指导我们,但最终我们必须决定在项目中实施它是否真的有益。 我坚信KISS原则

演示地址

If you like the video, please do share it, like it and subscribe to my channel. If you think I am mistaken or you have any comments or feedback so that I can improve my videos in future, please let me know through comments here or on YouTube video page.

如果您喜欢该视频,请共享它并订阅我的频道。 如果您认为我有误,或者有任何意见或反馈,以便将来可以改进自己的视频,请通过此处或YouTube视频页面上的评论让我知道。

JDK中的Builder设计模式示例 (Builder Design Pattern Example in JDK)

Some of the builder pattern example in Java classes are;

Java类中的一些构建器模式示例为:

  • java.lang.StringBuilder#append() (unsynchronized)

    java.lang.StringBuilder#append()(未同步)
  • java.lang.StringBuffer#append() (synchronized)

    java.lang.StringBuffer#append()(已同步)

That’s all for builder design pattern in java.

这就是Java中的构建器设计模式。

GitHub Repository. GitHub Repository下载示例代码。

翻译自: https://www.journaldev.com/1425/builder-design-pattern-in-java

java 生成器 设计模式

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值