Thomas Darimont
Erfahrenes Mitglied
Hallo,
dieser Beitrag erklärt das erzeugende Muster: Builder
Ausgabe:
Gruß Tom
dieser Beitrag erklärt das erzeugende Muster: Builder
Java:
package de.tutorials.design.patterns.creational;
import java.util.LinkedHashSet;
import java.util.Set;
import org.jpatterns.gof.BuilderPattern.Builder;
import org.jpatterns.gof.BuilderPattern.ConcreteBuilder;
import org.jpatterns.gof.BuilderPattern.Director;
import org.jpatterns.gof.BuilderPattern.Product;
import static de.tutorials.design.patterns.creational.BuilderPatternExample.TeamBuilder.newTeam;
public class BuilderPatternExample {
public static void main(String[] args) {
Team dreamTeam = new Coach().makeNewTeam(newTeam());
System.out.println(dreamTeam);
}
@Builder
public static interface ITeamBuilder{
Team get();
ITeamBuilder challenge();
ITeamBuilder educate();
ITeamBuilder motivate();
ITeamBuilder add(Member member);
}
@ConcreteBuilder
public static class TeamBuilder implements ITeamBuilder{
protected Team team = new Team();
public ITeamBuilder add(Member member) {
team.members.add(member);
return this;
}
public ITeamBuilder motivate() {
team.motivation = new Motivation();
return this;
}
public ITeamBuilder educate() {
team.knowhow = new Knowhow();
return this;
}
public ITeamBuilder challenge() {
team.spirit = new Spirit();
return this;
}
public Team get() {
try {
return team;
} finally {
team = null;
}
}
public static ITeamBuilder newTeam() {
return new TeamBuilder();
}
}
static class TeamComponent{
public String toString() {
return getClass().getSimpleName() +": " + hashCode();
}
}
static class Spirit extends TeamComponent {}
static class Motivation extends TeamComponent {}
static class Knowhow extends TeamComponent {}
static class Member extends TeamComponent {}
@Product
static class Team {
protected Set<Member> members = new LinkedHashSet<BuilderPatternExample.Member>();
protected Spirit spirit;
protected Motivation motivation;
protected Knowhow knowhow;
@Override
public String toString() {
return "Team [members=" + members + ", spirit=" + spirit + ", motivation=" + motivation + ", knowhow="
+ knowhow + "]";
}
}
@Director
static class Coach{
public Team makeNewTeam(ITeamBuilder builder){
Team team = TeamBuilder
.newTeam()
.add(new Member())
.add(new Member())
.add(new Member())
.add(new Member())
.add(new Member())
.motivate()
.educate()
.add(new Member())
.challenge()
.get();
return team;
}
}
}
Ausgabe:
Code:
Team [members=[Member: 1169863946, Member: 1690552137, Member: 1901116749, Member: 1807500377, Member: 355165777, Member: 778966024], spirit=Spirit: 1383884648, motivation=Motivation: 1701381926, knowhow=Knowhow: 1381270477]
Gruß Tom