返回

工厂模式与策略模式比较分析

后端

工厂模式是一种创建型设计模式,它为创建对象提供了一种统一的接口,从而使创建对象的过程与对象的实际实现分离。换言之,工厂模式使您可以轻松地创建不同类型的对象,而无需关心这些对象是如何创建的。

策略模式是一种行为型设计模式,它将算法和数据分离,从而使算法可以独立于数据而变化。换言之,策略模式使您可以轻松地改变算法,而无需修改使用该算法的代码。

工厂模式与策略模式的区别

特性 工厂模式 策略模式
目的 创建对象 选择算法
关注点 对象的创建过程 算法的选择
何时使用 当您需要创建不同类型的对象时 当您需要改变算法时
优点 提高代码的可扩展性、可重用性和可维护性 提高代码的可扩展性、可重用性和可维护性
缺点 可能会导致代码更复杂 可能会导致代码更复杂

工厂模式的实现

// 接口
interface Shape {
    void draw();
}

// 实现类
class Circle implements Shape {
    public void draw() {
        System.out.println("Draw a circle.");
    }
}

class Square implements Shape {
    public void draw() {
        System.out.println("Draw a square.");
    }
}

// 工厂类
class ShapeFactory {
    public Shape getShape(String shapeType) {
        if (shapeType.equals("circle")) {
            return new Circle();
        } else if (shapeType.equals("square")) {
            return new Square();
        } else {
            return null;
        }
    }
}

// 测试类
public class Test {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();

        Shape circle = shapeFactory.getShape("circle");
        circle.draw();

        Shape square = shapeFactory.getShape("square");
        square.draw();
    }
}

策略模式的实现

// 接口
interface Strategy {
    void doSomething();
}

// 实现类
class ConcreteStrategyA implements Strategy {
    public void doSomething() {
        System.out.println("Do something A.");
    }
}

class ConcreteStrategyB implements Strategy {
    public void doSomething() {
        System.out.println("Do something B.");
    }
}

// 上下文类
class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void doSomething() {
        strategy.doSomething();
    }
}

// 测试类
public class Test {
    public static void main(String[] args) {
        Context context = new Context(new ConcreteStrategyA());
        context.doSomething();

        context = new Context(new ConcreteStrategyB());
        context.doSomething();
    }
}