一、建造者模式.
1、MyBatis框架的环境类创建,通过静态内部类实现.
public final class Environment {
// 环境ID
private final String id;
// 事务工厂
private final TransactionFactory transactionFactory;
// 数据源
private final DataSource dataSource;
public Environment(String id, TransactionFactory transactionFactory, DataSource dataSource) {
// 1、构造方法中做一些必要的参数校验
if (id == null) {
throw new IllegalArgumentException("Parameter 'id' must not be null");
}
if (transactionFactory == null) {
throw new IllegalArgumentException("Parameter 'transactionFactory' must not be null");
}
this.id = id;
if (dataSource == null) {
throw new IllegalArgumentException("Parameter 'dataSource' must not be null");
}
this.transactionFactory = transactionFactory;
this.dataSource = dataSource;
}
// 2、静态内部类实现Builder
public static class Builder {
private String id;
private TransactionFactory transactionFactory;
private DataSource dataSource;
public Builder(String id) {
this.id = id;
}
public Builder transactionFactory(TransactionFactory transactionFactory) {
this.transactionFactory = transactionFactory;
return this;
}
public Builder dataSource(DataSource dataSource) {
this.dataSource = dataSource;
return this;
}
public String id() {
return this.id;
}
// 3、建造者
public Environment build() {
return new Environment(this.id, this.transactionFactory, this.dataSource);
}
}
public String getId() {
return this.id;
}
public TransactionFactory getTransactionFactory() {
return this.transactionFactory;
}
public DataSource getDataSource() {
return this.dataSource;
}
}
使用方式:
new Environment.Builder(id).transactionFactory(xx).dataSource(xx).build();
2、Swagger的接口管理的建造者模式,通过外部类来实现.
// 定义接口管理基本信息
public ApiInfo(
String title,
String description,
String version,
String termsOfServiceUrl,
Contact contact,
String license,
String licenseUrl,
Collection<VendorExtension> vendorExtensions) {
this.title = title;
this.description = description;
this.version = version;
this.termsOfServiceUrl = termsOfServiceUrl;
this.contact = contact;
this.license = license;
this.licenseUrl = licenseUrl;
this.vendorExtensions = new ArrayList<>(vendorExtensions);
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getTermsOfServiceUrl() {
return termsOfServiceUrl;
}
public Contact getContact() {
return contact;
}
public String getLicense() {
return license;
}
public String getLicenseUrl() {
return licenseUrl;
}
public String getVersion() {
return version;
}
public List<VendorExtension> getVendorExtensions() {
return vendorExtensions;
}
}
// 定义建造者类
public class ApiInfoBuilder {
private String title;
private String description;
private String termsOfServiceUrl;
private Contact contact;
private String license;
private String licenseUrl;
private String version;
private final List<VendorExtension> vendorExtensions = new ArrayList<>();
/**
* Updates the api title
*
* @param title - title for the API
* @return this
*/
public ApiInfoBuilder title(String title) {
this.title = title;
return this;
}
/**
* Updates the api description
*
* @param description - api description
* @return this
*/
public ApiInfoBuilder description(String description) {
this.description = description;
return this;
}
/**
* Updates the terms of service url
*
* @param termsOfServiceUrl - url to the terms of service
* @return this
*/
public ApiInfoBuilder termsOfServiceUrl(String termsOfServiceUrl) {
this.termsOfServiceUrl = termsOfServiceUrl;
return this;
}
/**
* Updates the api version
*
* @param version - of the API
* @return this
*/
public ApiInfoBuilder version(String version) {
this.version = version;
return this;
}
/**
* Updates contact information for the person responsible for this API
*
* @param contact - contact information
* @return this
*/
public ApiInfoBuilder contact(Contact contact) {
this.contact = contact;
return this;
}
/**
* Updates license information for this API
*
* @param license licence string
* @return this
*/
public ApiInfoBuilder license(String license) {
this.license = license;
return this;
}
/**
* Updates the license Url for this API
*
* @param licenseUrl - license Url
* @return this
*/
public ApiInfoBuilder licenseUrl(String licenseUrl) {
this.licenseUrl = licenseUrl;
return this;
}
/**
* Adds extensions for this API
*
* @param extensions - extensions
* @return this
*/
public ApiInfoBuilder extensions(List<VendorExtension> extensions) {
this.vendorExtensions.addAll(nullToEmptyList(extensions));
return this;
}
public ApiInfo build() {
return new ApiInfo(title, description, version, termsOfServiceUrl, contact, license, licenseUrl, vendorExtensions);
}
}
使用方式:
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Swagger3.x接口文档").description("项目前后端接口文档").contact(new Contact("Jack", "https://XXX", "xxx@qq.com"))
.version("1.0.0").build();
}
3、Nacos的实例构造器建造者模式.
package com.alibaba.nacos.api.naming.pojo;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.alibaba.nacos.api.utils.StringUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import static com.alibaba.nacos.api.common.Constants.NUMBER_PATTERN;
/**
* Instance.
*
* @author nkorange
*/
@JsonInclude(Include.NON_NULL)
public class Instance implements Serializable {
private static final long serialVersionUID = -742906310567291979L;
/**
* unique id of this instance.
*/
private String instanceId;
/**
* instance ip.
*/
private String ip;
/**
* instance port.
*/
private int port;
/**
* instance weight.
*/
private double weight = 1.0D;
/**
* instance health status.
*/
private boolean healthy = true;
/**
* If instance is enabled to accept request.
*/
private boolean enabled = true;
/**
* If instance is ephemeral.
*
* @since 1.0.0
*/
private boolean ephemeral = true;
/**
* cluster information of instance.
*/
private String clusterName;
/**
* Service information of instance.
*/
private String serviceName;
/**
* user extended attributes.
*/
private Map<String, String> metadata = new HashMap<String, String>();
public String getInstanceId() {
return this.instanceId;
}
public void setInstanceId(final String instanceId) {
this.instanceId = instanceId;
}
public String getIp() {
return this.ip;
}
public void setIp(final String ip) {
this.ip = ip;
}
public int getPort() {
return this.port;
}
public void setPort(final int port) {
this.port = port;
}
public double getWeight() {
return this.weight;
}
public void setWeight(final double weight) {
this.weight = weight;
}
public boolean isHealthy() {
return this.healthy;
}
public void setHealthy(final boolean healthy) {
this.healthy = healthy;
}
public String getClusterName() {
return this.clusterName;
}
public void setClusterName(final String clusterName) {
this.clusterName = clusterName;
}
public String getServiceName() {
return this.serviceName;
}
public void setServiceName(final String serviceName) {
this.serviceName = serviceName;
}
public Map<String, String> getMetadata() {
return this.metadata;
}
public void setMetadata(final Map<String, String> metadata) {
this.metadata = metadata;
}
/**
* add meta data.
*
* @param key meta data key
* @param value meta data value
*/
public void addMetadata(final String key, final String value) {
if (metadata == null) {
metadata = new HashMap<String, String>(4);
}
metadata.put(key, value);
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
public boolean isEphemeral() {
return this.ephemeral;
}
public void setEphemeral(final boolean ephemeral) {
this.ephemeral = ephemeral;
}
@Override
public String toString() {
return "Instance{" + "instanceId='" + instanceId + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", weight="
+ weight + ", healthy=" + healthy + ", enabled=" + enabled + ", ephemeral=" + ephemeral
+ ", clusterName='" + clusterName + '\'' + ", serviceName='" + serviceName + '\'' + ", metadata="
+ metadata + '}';
}
public String toInetAddr() {
return ip + ":" + port;
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof Instance)) {
return false;
}
final Instance host = (Instance) obj;
return Instance.strEquals(host.toString(), toString());
}
@Override
public int hashCode() {
return toString().hashCode();
}
private static boolean strEquals(final String str1, final String str2) {
return str1 == null ? str2 == null : str1.equals(str2);
}
public long getInstanceHeartBeatInterval() {
return getMetaDataByKeyWithDefault(PreservedMetadataKeys.HEART_BEAT_INTERVAL,
Constants.DEFAULT_HEART_BEAT_INTERVAL);
}
public long getInstanceHeartBeatTimeOut() {
return getMetaDataByKeyWithDefault(PreservedMetadataKeys.HEART_BEAT_TIMEOUT,
Constants.DEFAULT_HEART_BEAT_TIMEOUT);
}
public long getIpDeleteTimeout() {
return getMetaDataByKeyWithDefault(PreservedMetadataKeys.IP_DELETE_TIMEOUT,
Constants.DEFAULT_IP_DELETE_TIMEOUT);
}
public String getInstanceIdGenerator() {
return getMetaDataByKeyWithDefault(PreservedMetadataKeys.INSTANCE_ID_GENERATOR,
Constants.DEFAULT_INSTANCE_ID_GENERATOR);
}
/**
* Returns {@code true} if this metadata contains the specified key.
*
* @param key metadata key
* @return {@code true} if this metadata contains the specified key
*/
public boolean containsMetadata(final String key) {
if (getMetadata() == null || getMetadata().isEmpty()) {
return false;
}
return getMetadata().containsKey(key);
}
private long getMetaDataByKeyWithDefault(final String key, final long defaultValue) {
if (getMetadata() == null || getMetadata().isEmpty()) {
return defaultValue;
}
final String value = getMetadata().get(key);
if (!StringUtils.isEmpty(value) && value.matches(NUMBER_PATTERN)) {
return Long.parseLong(value);
}
return defaultValue;
}
private String getMetaDataByKeyWithDefault(final String key, final String defaultValue) {
if (getMetadata() == null || getMetadata().isEmpty()) {
return defaultValue;
}
return getMetadata().get(key);
}
}
package com.alibaba.nacos.api.naming.pojo.builder;
import com.alibaba.nacos.api.naming.pojo.Instance;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* Builder for {@link Instance}.
*
* @author xiweng.yy
*/
public class InstanceBuilder {
private String instanceId;
private String ip;
private Integer port;
private Double weight;
private Boolean healthy;
private Boolean enabled;
private Boolean ephemeral;
private String clusterName;
private String serviceName;
private Map<String, String> metadata = new HashMap<>();
private InstanceBuilder() {
}
public InstanceBuilder setInstanceId(String instanceId) {
this.instanceId = instanceId;
return this;
}
public InstanceBuilder setIp(String ip) {
this.ip = ip;
return this;
}
public InstanceBuilder setPort(Integer port) {
this.port = port;
return this;
}
public InstanceBuilder setWeight(Double weight) {
this.weight = weight;
return this;
}
public InstanceBuilder setHealthy(Boolean healthy) {
this.healthy = healthy;
return this;
}
public InstanceBuilder setEnabled(Boolean enabled) {
this.enabled = enabled;
return this;
}
public InstanceBuilder setEphemeral(Boolean ephemeral) {
this.ephemeral = ephemeral;
return this;
}
public InstanceBuilder setClusterName(String clusterName) {
this.clusterName = clusterName;
return this;
}
public InstanceBuilder setServiceName(String serviceName) {
this.serviceName = serviceName;
return this;
}
public InstanceBuilder setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
return this;
}
public InstanceBuilder addMetadata(String metaKey, String metaValue) {
this.metadata.put(metaKey, metaValue);
return this;
}
/**
* Build a new {@link Instance}.
*
* @return new instance
*/
public Instance build() {
Instance result = new Instance();
if (!Objects.isNull(instanceId)) {
result.setInstanceId(instanceId);
}
if (!Objects.isNull(ip)) {
result.setIp(ip);
}
if (!Objects.isNull(port)) {
result.setPort(port);
}
if (!Objects.isNull(weight)) {
result.setWeight(weight);
}
if (!Objects.isNull(healthy)) {
result.setHealthy(healthy);
}
if (!Objects.isNull(enabled)) {
result.setEnabled(enabled);
}
if (!Objects.isNull(ephemeral)) {
result.setEphemeral(ephemeral);
}
if (!Objects.isNull(clusterName)) {
result.setClusterName(clusterName);
}
if (!Objects.isNull(serviceName)) {
result.setServiceName(serviceName);
}
result.setMetadata(metadata);
return result;
}
public static InstanceBuilder newBuilder() {
return new InstanceBuilder();
}
}
使用方式如下:
// 构造器方式. Instance instance = InstanceBuilder.newBuilder().setInstanceId(XXX).build();
4、Nacos的缓存构造器
package com.alibaba.nacos.common.cache.builder;
import com.alibaba.nacos.common.cache.Cache;
import com.alibaba.nacos.common.cache.decorators.AutoExpireCache;
import com.alibaba.nacos.common.cache.decorators.LruCache;
import com.alibaba.nacos.common.cache.decorators.SynchronizedCache;
import com.alibaba.nacos.common.cache.impl.SimpleCache;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* Cache builder.
* @author zzq
* @date 2021/7/30
*/
public class CacheBuilder<K, V> {
private static final int DEFAULT_MAXIMUMSIZE = 1024;
private static final int DEFAULT_INITIALIZE_CAPACITY = 1024;
private static final int DEFAULT_EXPIRE_NANOS = -1;
private long expireNanos = DEFAULT_EXPIRE_NANOS;
private int maximumSize = DEFAULT_MAXIMUMSIZE;
private int initializeCapacity = DEFAULT_INITIALIZE_CAPACITY;
private boolean sync = false;
private boolean lru = false;
public static <K, V> CacheBuilder<K, V> builder() {
return new CacheBuilder<>();
}
/**
* Set expiration time.
*/
public CacheBuilder<K, V> expireNanos(long duration, TimeUnit unit) {
checkExpireNanos(duration, unit);
this.expireNanos = unit.toNanos(duration);
return this;
}
private void checkExpireNanos(long duration, TimeUnit unit) {
if (duration < 0) {
throw new IllegalArgumentException("duration cannot be negative");
}
if (Objects.isNull(unit)) {
throw new IllegalArgumentException("unit cannot be null");
}
}
/**
* Set the maximum capacity of the cache pair.
* @param maximumSize maximum capacity
*/
public CacheBuilder<K, V> maximumSize(int maximumSize) {
if (maximumSize < 0) {
throw new IllegalArgumentException("size cannot be negative");
}
this.maximumSize = maximumSize;
return this;
}
/**
* Set whether the cache method is synchronized.
* @param sync if sync value is true, each method of the constructed cache is synchronized.
*/
public CacheBuilder<K, V> sync(boolean sync) {
this.sync = sync;
return this;
}
/**
* Does the constructed cache support lru.
* @param lru If the cache built for true is a

本文详细介绍了Java中的建造者模式、模板方法、单例模式和工厂模式,以及Spring框架的标记接口。以MyBatis为例,展示了如何在框架中应用这些模式,如Environment类的构建、Swagger接口的构建、Nacos的实例和缓存构建器,以及TypeHandler的实现。此外,还探讨了Spring的ApplicationContextAware、BeanFactoryAware和BeanNameAware等标记接口的用途。
最低0.47元/天 解锁文章
849

被折叠的 条评论
为什么被折叠?



