Last active
March 11, 2017 12:15
-
-
Save mibrahimdev/5413b667cad12c94d01ff1b09c8528eb to your computer and use it in GitHub Desktop.
5 design patterns every Android developer should know - Builder pattern
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 Ship { | |
private String name; | |
private String area; | |
private int guns; | |
private int crew; | |
private String radarType; | |
//normal getters | |
public String getName() { | |
return name; | |
} | |
public String getArea() { | |
return area; | |
} | |
public int getGuns() { | |
return guns; | |
} | |
public int getCrew() { | |
return crew; | |
} | |
public String getRadarType() { | |
return radarType; | |
} | |
//private setters, we're using them to set fields in the builder | |
private void setRadarType(String radarType) { | |
this.radarType = radarType; | |
} | |
private void setName(String name) { | |
this.name = name; | |
} | |
private void setArea(String area) { | |
this.area = area; | |
} | |
private void setGuns(int guns) { | |
this.guns = guns; | |
} | |
private void setCrew(int crew) { | |
this.crew = crew; | |
} | |
//the Builder class | |
public static class Builder { | |
private Ship ship; | |
public Builder() { | |
ship = new Ship(); | |
} | |
public Builder setName(String name){ | |
ship.setName(name); | |
return this; | |
} | |
public Builder howManyGuns(int guns){ | |
ship.setGuns(guns); | |
return this; | |
} | |
public Builder setOperationArea(String area){ | |
ship.setArea(area); | |
return this; | |
} | |
public Builder howManyCrew(int crew){ | |
ship.setCrew(crew); | |
return this; | |
} | |
public Builder radarType(String radarType){ | |
ship.setRadarType(radarType); | |
return this; | |
} | |
//method to expose the created object | |
public Ship build(){ | |
return ship; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment