Skip to content

Instantly share code, notes, and snippets.

@stefanhoth
Forked from anonymous/gist:1571520dd1aa934fce28
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanhoth/5d6fa521aad322d15d44 to your computer and use it in GitHub Desktop.
Save stefanhoth/5d6fa521aad322d15d44 to your computer and use it in GitHub Desktop.
Simple Factory pattern
// The Factory
public final class VehicleFactory {
// private constructor => can't be instanciated, final can't be extended since the constructor is not reachable for a subclass
private VehicleFactory (){
// no-op
}
public static Vehicel Vehicle produceVehicle(String name, String manufacturer, int horsepowerInPS){
return new Vehicle(name, manufacturer, horsepowerInPS);
}
}
public class Vehicle {
private String name;
private String manufacturer;
private int horsepowerInPS;
// package local constructor -> only the factory in the same package can create instances
Vehicle (String name, String manufacturer, int horsepowerInPS) {
this.name = name;
this.manufacturer = manufacturer;
this.horsepowerInPS = horsepowerInPS;
}
public String getName(){
return name;
}
public String getManufacturer(){
return manufacturer;
}
public int getHorsepowerInPS(){
return horsepowerInPS;
}
@Override
public String toString() {
return String.format(Locale.US, "Vehicle: %s %s (%d PS)", manufacturer, name, horsepowerInPS);
}
}
// {...}
// The Client
public class ListCars {
private static List<AbstractVehicel> vehicelList = new ArrayList<>();
public static void main(String[] args) {
addVehicelToList();
new ListCars();
}
private static void addVehicleToList() {
vehicleList.add(VehicleFactory.produceVehicle("Mustang", "Ford", 310);
vehicleList.add(VehicleFactory.produceVehicle("Model S", "Tesla", 416);
vehicleList.add(VehicleFactory.produceVehicle("Golf GTI", "VW", 360);
vehicleList.add(VehicleFactory.produceVehicle("Cooper", "Mini", 134);
}
public ListCars() {
for(Vehicle vehicle : vehicleList) {
System.out.println("-----------------------------");
System.out.println(vehicle.toString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment