Last active
April 21, 2020 10:43
-
-
Save alexengrig/611a8ecefca32fd971f9996525b44584 to your computer and use it in GitHub Desktop.
Builder with Inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BuilderExample { | |
public static void main(String[] args) { | |
User user = new UserBuilder().id(1).name("One").build(); | |
} | |
} | |
class Entity { | |
protected int id; | |
public Entity(int id) { | |
this.id = id; | |
} | |
} | |
class User extends Entity { | |
protected String name; | |
public User(int id, String name) { | |
super(id); | |
this.name = name; | |
} | |
} | |
abstract class EntityBuilder<T extends Entity, B extends EntityBuilder<T, B>> { | |
protected int id; | |
protected abstract B self(); | |
public B id(int value) { | |
id = value; | |
return self(); | |
} | |
public abstract T build(); | |
} | |
class UserBuilder extends EntityBuilder<User, UserBuilder> { | |
protected String name; | |
@Override | |
protected UserBuilder self() { | |
return this; | |
} | |
public UserBuilder name(String value) { | |
name = value; | |
return this; | |
} | |
@Override | |
public User build() { | |
return new User(id, name); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment