// Product interface
interface Vehicle {
void drive();
}
// Concrete products
class Car implements Vehicle {
@Override
public void drive() {
System.out.println("Driving a car");
}
}
class Motorcycle implements Vehicle {
@Override
public void drive() {
System.out.println("Riding a motorcycle");
}
}
// Creator abstract class
abstract class VehicleFactory {
// Factory method
abstract Vehicle createVehicle();
// Operations using the factory method
public void deliverVehicle() {
Vehicle vehicle = createVehicle();
System.out.println("Delivering the vehicle:");
vehicle.drive();
}
}
// Concrete creators
class CarFactory extends VehicleFactory {
@Override
Vehicle createVehicle() {
return new Car();
}
}
class MotorcycleFactory extends VehicleFactory {
@Override
Vehicle createVehicle() {
return new Motorcycle();
}
}
// Client code
public class Main {
public static void main(String[] args) {
VehicleFactory carFactory = new CarFactory();
carFactory.deliverVehicle();
VehicleFactory motorcycleFactory = new MotorcycleFactory();
motorcycleFactory.deliverVehicle();
}
}
Delivering the vehicle:
Driving a car
Delivering the vehicle:
Riding a motorcycle
// Product interface
public interface Product {
void create();
}
public class Electronics implements Product {
@Override
public void create() {
System.out.println("Electronics product created.");
}
}
public class Clothing implements Product {
@Override
public void create() {
System.out.println("Clothing product created.");
}
}
public class Book implements Product {
@Override
public void create() {
System.out.println("Book product created.");
}
}
// ProductFactory class
public abstract class ProductFactory {
// Factory Method
public abstract Product createProduct(String type);
public Product orderProduct(String type) {
Product product = createProduct(type);
product.create();
return product;
}
}
// ConcreteProductFactory class (Concrete Factory)
public class ConcreteProductFactory extends ProductFactory {
@Override
public Product createProduct(String type) {
if (type.equalsIgnoreCase("electronics")) {
return new Electronics();
} else if (type.equalsIgnoreCase("clothing")) {
return new Clothing();
} else if (type.equalsIgnoreCase("book")) {
return new Book();
} else {
throw new IllegalArgumentException(
"Unknown product type."
);
}
}
}
public class Main {
public static void main(String[] args) {
ProductFactory factory = new ConcreteProductFactory();
// Create an electronics product
Product electronics = factory.orderProduct("electronics");
// Create a clothing product
Product clothing = factory.orderProduct("clothing");
// Create a book product
Product book = factory.orderProduct("book");
}
}
Electronics product created.
Clothing product created.
Book product created.