Fundamentals 8 min read

How Strategy and Factory Patterns Simplify Java Code: A Hands‑On Comparison

This article compares Java's Factory and Strategy design patterns, explaining their concepts, showing UML diagrams, providing complete code examples, and demonstrating how each pattern affects code structure, flexibility, and maintainability, while drawing parallels to micro‑service architecture.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
How Strategy and Factory Patterns Simplify Java Code: A Hands‑On Comparison

Preface

When first learning design patterns, the Singleton and Factory patterns are the most frequently used. After reading about Domain‑Driven Design (DDD), I started using the Strategy pattern, which together with Factory pattern reduces code redundancy and makes service‑layer code cleaner.

UML Diagram

The UML diagram shows little visual difference between the two patterns, so we examine the code directly.

Interface Definition

public interface People {
    void eat();
    void run();
    void wear();
}

Concrete Implementations

public class Xiaoming implements People {
    @Override
    public void eat() { System.out.println("小明吃饭"); }
    @Override
    public void run() { System.out.println("小明跑步"); }
    @Override
    public void wear() { System.out.println("小明穿衣"); }
}

public class Xiaohong implements People {
    @Override
    public void eat() { System.out.println("小红吃饭"); }
    @Override
    public void run() { System.out.println("小红跑步"); }
    @Override
    public void wear() { System.out.println("小红穿衣"); }
}

Simple Factory Pattern

public class PeopleFactory {
    public People getPeople(String name) {
        if (name.equals("Xiaoming")) {
            return new Xiaoming();
        } else if (name.equals("Xiaohong")) {
            return new Xiaohong();
        }
        return null;
    }
}

Strategy Pattern

public class StrategySign {
    private People people;
    public StrategySign(People people) { this.people = people; }
    public StrategySign(String name) {
        if (name.equals("Xiaoming")) {
            this.people = new Xiaoming();
        } else if (name.equals("Xiaohong")) {
            this.people = new Xiaohong();
        }
    }
    public void run() { people.run(); }
}

Test Execution

@Test
public void testSign() {
    PeopleFactory peopleFactory = new PeopleFactory();
    People people = peopleFactory.getPeople("Xiaohong");
    System.out.print("工厂模式-------------");
    people.run();
    StrategySign strategySign = new StrategySign("Xiaohong");
    System.out.print("策略模式-------------");
    strategySign.run();
}

The output of both patterns is identical, but their internal mechanisms differ.

Comparison of the Two Patterns

Factory pattern focuses on returning an instance of a concrete implementation; the client calls methods on the returned object without concern for the creation process. Strategy pattern creates the concrete strategy up front, allowing the client to compose or replace behavior dynamically, emphasizing the process rather than just the result.

For example, if we want "Xiaohong" to eat, run, then eat again, the Factory approach would require separate test cases for each sequence, whereas the Strategy approach can encapsulate the entire sequence in a single method.

Extended Strategy Example

public class StrategySign {
    private People people;
    public StrategySign(People people) { this.people = people; }
    public StrategySign(String name) {
        if (name.equals("Xiaoming")) {
            this.people = new Xiaoming();
        } else if (name.equals("Xiaohong")) {
            this.people = new Xiaohong();
        }
    }
    public void run() {
        people.eat();
        people.run();
        people.eat();
    }
}
@Test
public void testSign() {
    PeopleFactory peopleFactory = new PeopleFactory();
    People people = peopleFactory.getPeople("Xiaohong");
    System.out.print("工厂模式-------------");
    people.eat();
    System.out.print("工厂模式-------------");
    people.run();
    System.out.print("工厂模式-------------");
    people.eat();
    StrategySign strategySign = new StrategySign("Xiaohong");
    System.out.print("策略模式-------------");
    strategySign.run();
}

While both patterns can achieve the same outcomes, the Strategy pattern offers greater flexibility and reduces code duplication when business logic becomes complex.

Conclusion

Strategy pattern shares similarities with micro‑service architecture: each method (eat, run, wear) can be seen as an independent service that can be composed to form new workflows, promoting decoupling and maintainability.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSoftware ArchitectureStrategy PatternFactory Pattern
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.