June 2018
Intermediate to advanced
280 pages
7h 46m
English
Let's write a simple factory to create instances of vehicles. We have an abstract Vehicle class and three concrete classes inherited from it: Bike, Car, and Truck. The factory, also called the static factory, will look like this:
public class VehicleFactory { public enum VehicleType { Bike,Car,Truck } public static Vehicle create(VehicleType type) { if (type.equals(VehicleType.Bike)) return new Bike(); if (type.equals(VehicleType.Car)) return new Car(); if (type.equals(VehicleType.Truck)) return new Truck(); else return null; }}
The factory looks very simple and is responsible for the instantiation of the vehicle classes, complying with the single responsibility principle. It helps us to reduce coupling because the client depends ...
Read now
Unlock full access