Explain Codes LogoExplain Codes Logo

What is the difference between Factory and Strategy patterns?

design-patterns
factory-pattern
strategy-pattern
object-creation
Alex KataevbyAlex Kataev·Sep 7, 2024
TLDR

The Factory pattern centralizes object creation, hiding the logic of instantiation and returning new objects from a given interface. Meanwhile, the Strategy pattern allows for algorithm interchangeability at runtime, providing different implementations of a common interface, which can be used by the client code.

// Factory pattern public interface Vehicle { void start(); } public class Car implements Vehicle { public void start() { /* Vroom Vroom! */ } } public class Bike implements Vehicle { public void start() { /* Let's pedal! */ } } public class VehicleFactory { public static Vehicle createVehicle(String type) { if ("car".equals(type)) return new Car(); else if ("bike".equals(type)) return new Bike(); throw new IllegalArgumentException("Is that a vehicle or a spaceship?"); } } // Strategy pattern public interface SortingStrategy { void sort(int[] data); } public class QuickSort implements SortingStrategy { public void sort(int[] data) {/* Fast as a Ferrari! */} } public class MergeSort implements SortingStrategy { public void sort(int[] data) {/* Methodical as a librarian! */} } public class ArrayProcessor { private SortingStrategy sorter; public ArrayProcessor(SortingStrategy sorter) { this.sorter = sorter; } public void sortData(int[] data) { sorter.sort(data); } }

Delving Deeper: Factory and Strategy Patterns

Strategic Factories

While Factory is for object creation and Strategy is for algorithm selection, they can effectively work together to deliver flexible designs. A RendererFactory might create a HighQualityRenderer or a PerformanceRenderer based on the strategy implemented. The best of both worlds!

Dynamic Duos

Factories are not just assembly lines for object creation—they can be strategic! A ConnectionPoolFactory could employ strategies like CachingStrategy, LoadBalancingStrategy or FailoverStrategy. Each strategy can adapt to factors like system load and network conditions.

Interface-Leveraging Patterns

Both Factory and Strategy patterns target interfaces rather than concrete classes. Factories generate concrete instances of a common interface, and strategies use this interface to interchange algorithms. This reduces dependencies and enhances maintainability.

Practical Use Cases

In GUI Development: A WidgetFactory creates Button, Checkbox, or other widgets while a LayoutStrategy organizes them for different UX requirements.

For Payment Processing: Different PaymentProcessor instances created by a Factory can use different SecurityStrategy instances at runtime to handle encryption and data protection.

The Power of Polymorphism

Adaptive Factories

Abstract Factory, with its ability to create families of objects, can use different strategies to adapt object creation to different environments. Think WindowsButtonCreationFactory and LinuxButtonCreationFactory for platform-specific UI components.

Strategy Pattern's Flexibility

The Strategy pattern encapsulates behavior, offering interchangeability that isn't available with static methods. By swapping out strategies at runtime without changing client code, adaptability is enhanced. Especially valuable when the system's behavior must change in real time.

Evolving with Requirements

Both Factory and Strategy patterns help you anticipate changes, through modular design. As requirements change, extend factories for new object types and add new strategies without rewriting existing code.