Sobes.tech
Middle

What is the Factory design pattern and how is it used in application development?

sobes.tech AI

Answer from AI

The 'Factory' pattern (Factory Method) is a creational pattern that defines an interface for creating an object but allows subclasses to decide which class to instantiate. The object creation method is encapsulated in a separate "factory" method.

It is used in application development for:

  • Encapsulating object creation logic: Client code does not depend on specific classes of created objects.
  • Extensibility: Easily add new object types without changing client code, just create a new factory subclass.
  • Polymorphism: Allows working with different subtypes of objects uniformly through a common interface.

Example of usage in Android:

  • Creating View Holders in RecyclerView.Adapter: onCreateViewHolder is essentially a factory method that returns a specific ViewHolder.
// Product interface
interface Transport {
    void deliver();
}

// Concrete product 1
class Truck implements Transport {
    @Override
    public void deliver() {
        // Delivery logic on truck
    }
}

// Concrete product 2
class Ship implements Transport {
    @Override
    public void deliver() {
        // Delivery logic on ship
    }
}

// Abstract factory
abstract class Logistics {
    public void planDelivery() {
        Transport t = createTransport(); // Factory method
        t.deliver();
    }

    // Abstract factory method to be implemented by subclasses
    abstract Transport createTransport();
}

// Concrete factory for land logistics
class RoadLogistics extends Logistics {
    @Override
    Transport createTransport() {
        return new Truck();
    }
}

// Concrete factory for sea logistics
class SeaLogistics extends Logistics {
    @Override
    Transport createTransport() {
        return new Ship();
    }
}

// Client code
class App {
    public static void main(String[] args) {
        Logistics roadLogistics = new RoadLogistics();
        roadLogistics.planDelivery(); // Creates Truck and calls deliver()

        Logistics seaLogistics = new SeaLogistics();
        seaLogistics.planDelivery(); // Creates Ship and calls deliver()
    }
}
What is the Factory design pattern and how is it used… - sobes.tech