-
-
Save stefanhoth/5d6fa521aad322d15d44 to your computer and use it in GitHub Desktop.
Simple Factory 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
// 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