Design Patterns - Factory

Factory

Problem - Create various type of cars like Sedan, SUV etc.

Solution -
interface CarFactory {
    public Car makeCar();
}
 
interface Car {
    public String getType();
}
 
/* Concrete implementations of the factory and car */
 
class SedanFactory implements CarFactory {
    public Car makeCar() {
        return new Sedan();
    }
}
 
class Sedan implements Car {
    public String getType() {
        return 'Sedan';
    }
}

 
// Client
public class Client{
	public static void main(String args[]){
		CarFactory factory = new SedanFactory();
		Car car = factory.makeCar();
		System.out.println(car.getType());
	}
}