Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
public Account build() {
Account account = new Account();
account.userId = Account.this.userId;
account.token = Account.this.token;
return account;
}
Ведь иммутабельности тут нет
без final на полях Вы не получите от JVM тех же гарантий видимости для многопоточного кода
Разве что компилятор решит сделать inline методу, хотя я уверен, что на публичный метод у него рука не поднимется.
Account acc = Account.newBuildler().setToken(a).setUserId(b).build();
this.account = acc;
doSomeAction(acc);
Account acc = new Account();
this.acc = acc;
<вот тут из другого потока происходит чтение token, и он получает null...>
acc.token = a;
acc.userId = b;
doSomeAction(acc);
Исходя из каких убеждений вы сделали эти утверждения?
Account.Builder builder = Account.newBuilder();
Account account = builder
.setToken("hello")
.setUserId("habr")
.build();
assert account.getToken().equals("hello"); // ok
builder.setToken("blablabla");
assert account.getToken().equals("hello"); // ой
Account account = Account.newBuilder().setToken("hello").setUserId("habr").build();
@Getter
@Builder
public class Account {
private String userId;
private String token;
}
@Getter
public class Account {
private final String userId;
private final String token;
@Builder
private Account(String userId, String token) {
this.userId = userId;
this.token = token;
}
}
Account.builder().userId("u12").token("t12").build();
public class Account {
private String userId;
private String token;
private Account() {}
// getters
// builder fabric method
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Account account = new Account();
public Account build() {
Account result = account;
account = new Account();
return result;
}
public Builder userId(String userId) {
account.userId = userId;
return this;
}
public Builder token(String token) {
account.token = token;
return this;
}
}
}
// usage
Account account = Account.builder().userId(someId).token(someToken).build();
Account.Builder builder = Account.builder();
Account accountOne = builder.userId("1").token("t1").build();
Account accountTwo = builder.userId("2").build(); // token will be null
public class Person
{
public string LastName { get; private set; }
public string FirstName { get; private set; }
public string MiddleName { get; private set; }
public string Salutation { get; private set; }
public string Suffix { get; private set; }
public string StreetAddress { get; private set; }
public string City { get; private set; }
public string State { get; private set; }
public bool IsFemale { get; private set; }
public bool IsEmployed { get; private set; }
public bool IsHomeOwner { get; private set; }
public Person (string lastName = "",
string firstName = "",
string middleName = "",
string salutation = "",
string suffix = "",
string streetAddress = "",
string city = "",
string state = "",
bool isFemale = false,
bool isEmployed = false,
bool isHomeOwner = false)
{
LastName = lastName;
FirstName = firstName;
MiddleName = middleName;
Salutation = salutation;
Suffix = suffix;
StreetAddress = streetAddress;
City = city;
State = state;
IsFemale = isFemale;
IsEmployed = isEmployed;
IsHomeOwner = isHomeOwner;
}
}
public class Person
{
public readonly string LastName { get; }
public readonly string FirstName { get; }
public readonly string MiddleName { get; }
public readonly string Salutation { get; }
public readonly string Suffix { get; }
public readonly string StreetAddress { get; }
public readonly string City { get; }
public readonly string State { get; }
public readonly bool IsFemale { get; }
public readonly bool IsEmployed { get; }
public readonly bool IsHomeOwner { get; }
public Person (string lastName = "",
string firstName = "",
string middleName = "",
string salutation = "",
string suffix = "",
string streetAddress = "",
string city = "",
string state = "",
bool isFemale = false,
bool isEmployed = false,
bool isHomeOwner = false)
{
LastName = lastName;
FirstName = firstName;
MiddleName = middleName;
Salutation = salutation;
Suffix = suffix;
StreetAddress = streetAddress;
City = city;
State = state;
IsFemale = isFemale;
IsEmployed = isEmployed;
IsHomeOwner = isHomeOwner;
}
}
public class Person(
string lastName = null,
string firstName = null,
string middleName = null,
string salutation = null,
string suffix = null,
string streetAddress = null,
string city = null,
string state = null,
bool isFemale = false,
bool isEmployed = false,
bool isHomeOwner = false)
{
public readonly string LastName { get; } = lastName;
public readonly string FirstName { get; } = firstName;
public readonly string MiddleName { get; } = middleName;
public readonly string Salutation { get; } = salutation;
public readonly string Suffix { get; } = suffix;
public readonly string StreetAddress { get; } = streetAddress;
public readonly string City { get; } = city;
public readonly string State { get; } = state;
public readonly bool IsFemale { get; } = isFemale;
public readonly bool IsEmployed { get; } = isEmployed;
public readonly bool IsHomeOwner { get; } = isHomeOwner;
}
var person = new Person(
lastName: "John",
firstName: "Smith",
city: "New York",
state: "New Tork");
Пока дотнет нормально не работает под никсы, вам эти технологии не доступны.
public class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private NameGenerator nameGenerator = new RandomNameGenerator();
private Integer age;
private Builder age(int age) {
this.age = age;
return this;
}
public Builder birthDate(Calendar date) {
return age(Calendar.getInstance().get(Calendar.YEAR) - date.get(Calendar.YEAR));
}
public Builder name(String name) {
return nameGenerator(new FixedNameGenerator(name));
}
public Builder nameGenerator(NameGenerator generator) {
this.nameGenerator = generator;
return this;
}
public Person build() {
if (age == null) {
throw new IllegalArgumentException();
}
return new Person(nameGenerator.generate(), age);
}
}
public static void main(String[] args) {
Person person = Person.builder().age(10).build();
}
}
public interface IBuilder<T> {
public T build();
}
public interface IPersonBuilder extends IBuilder<Person>
{
public IPersonBuilder age(int value);
}
Builder.newBuilder(IPersonBuilder.class).age(10).build();
Элегантный Builder на Java