设计模式:工厂、策略、责任链模式

1.工厂模式(Factory Pattern)

目的: 工厂模式是一种创建型设计模式,它提供了一个创建对象的接口,但让子类决定实例化哪一个类。工厂模式的主要目的是为了将对象的创建和使用相分离,以便于客户程序无需知道对象是如何被创建的,只需关心接口即可。

结构

  • Factory(抽象工厂):定义创建对象的接口,声明一个创建产品对象的方法。
  • ConcreteFactory(具体工厂):实现抽象工厂接口,负责创建具体的产品对象。
  • Product(产品接口/抽象类):定义了产品的接口,所有具体产品必须遵循该接口。
  • ConcreteProduct(具体产品):实现了产品接口的具体类,是工厂创建的目标对象。

示例场景: 在支付系统的例子中,可以有一个支付处理器工厂,根据不同需求创建不同的支付处理器对象,如信用卡支付处理器、支付宝支付处理器等。假设我们有一个动物接口及其若干实现类,我们希望创建一个工厂来根据名称生成不同种类的动物对象。

// 产品接口
interface Animal {
    void makeSound();
}

// 具体产品
class Dog implements Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog barks.");
    }
}

class Cat implements Animal {
    @Override
    public void makeSound() {
        System.out.println("Cat meows.");
    }
}

// 抽象工厂
abstract class AnimalFactory {
    abstract Animal createAnimal(String type);
}

// 具体工厂
class AnimalFactoryImpl extends AnimalFactory {
    @Override
    Animal createAnimal(String type) {
        if ("dog".equalsIgnoreCase(type)) {
            return new Dog();
        } else if ("cat".equalsIgnoreCase(type)) {
            return new Cat();
        } else {
            throw new IllegalArgumentException("Invalid animal type");
        }
    }
}

// 客户端代码
public class FactoryMethodExample {
    public static void main(String[] args) {
        AnimalFactory factory = new AnimalFactoryImpl();
        Animal myDog = factory.createAnimal("dog");
        Animal myCat = factory.createAnimal("cat");

        myDog.makeSound(); // 输出:Dog barks.
        myCat.makeSound(); // 输出:Cat meows.
    }
}

2.策略模式(Strategy Pattern)

目的: 策略模式是一种行为设计模式,它定义了一系列算法族,并分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。策略模式提供了对“开闭原则”的支持,即对扩展开放,对修改关闭。

结构

  • Strategy(策略接口/抽象类):定义了所有支持的算法的公共接口。
  • ConcreteStrategy(具体策略类):实现了策略接口的一个或多个算法变体。
  • Context(上下文):使用策略接口来调用具体策略类的算法,并在运行时决定使用哪种策略。

示例场景: 在电商系统中,优惠策略可以采用策略模式,各种具体的优惠策略(如满减策略、打折策略、买赠策略)都是具体策略类,而购物车结算时根据不同的活动规则动态选择并应用相应的优惠策略。假设我们有一个计算折扣的系统,可以有不同的折扣策略。

// 策略接口
interface DiscountStrategy {
    double calculateDiscount(double price);
}

// 具体策略
class NormalDiscount implements DiscountStrategy {
    @Override
    public double calculateDiscount(double price) {
        return price * 0.9; // 提供正常九折优惠
    }
}

class VIPDiscount implements DiscountStrategy {
    @Override
    public double calculateDiscount(double price) {
        return price * 0.8; // 提供VIP八折优惠
    }
}

// 上下文
class ShoppingCart {
    private DiscountStrategy strategy;

    public ShoppingCart(DiscountStrategy strategy) {
        this.strategy = strategy;
    }

    public double applyDiscount(double price) {
        return strategy.calculateDiscount(price);
    }

    public void setDiscountStrategy(DiscountStrategy strategy) {
        this.strategy = strategy;
    }
}

// 客户端代码
public class StrategyPatternExample {
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart(new NormalDiscount());
        System.out.println(cart.applyDiscount(100)); // 输出:90.0

        cart.setDiscountStrategy(new VIPDiscount());
        System.out.println(cart.applyDiscount(100)); // 输出:80.0
    }
}

3.责任链模式(Chain of Responsibility Pattern)

目的: 责任链模式是一种行为设计模式,它将请求的发送者与接收者解耦,使多个对象都有机会处理请求。请求沿着一条链传递,直到链上的某个对象处理它为止。

结构

  • Handler(抽象处理者):定义处理请求的接口,通常会包含一个指向下一个处理者的引用。
  • ConcreteHandler(具体处理者):实现抽象处理者的处理请求方法,可以处理请求,也可能将请求传递给链中的下一个处理者。
  • Request(请求):封装了具体请求信息。

示例场景: 在审批流程系统中,各个级别的管理者(具体处理者)形成一个责任链,当员工提交一项请求时,请求从最低级别开始逐级向上审批,直至找到有权处理的处理者为止。若当前处理者不能处理,则将请求转发给上一级别处理者。假设我们有一个请假申请审批系统,各级领导可以批准或拒绝假期请求,或者将其转发给上级。

// 请求
class LeaveRequest {
    private int days;
    private String reason;

    public LeaveRequest(int days, String reason) {
        this.days = days;
        this.reason = reason;
    }

    public int getDays() {
        return days;
    }

    public String getReason() {
        return reason;
    }
}

// 处理者接口
interface Approver {
    void processRequest(LeaveRequest request);
    void setSuccessor(Approver successor);
}

// 具体处理者
class Manager implements Approver {
    private Approver nextApprover;

    @Override
    public void processRequest(LeaveRequest request) {
        if (request.getDays() <= 5) {
            System.out.println("Manager approved the leave.");
        } else {
            if (nextApprover != null) {
                nextApprover.processRequest(request);
            } else {
                System.out.println("No one can approve this leave.");
            }
        }
    }

    @Override
    public void setSuccessor(Approver successor) {
        this.nextApprover = successor;
    }
}

class Director implements Approver {
    private Approver nextApprover;

    @Override
    public void processRequest(LeaveRequest request) {
        if (request.getDays() <= 10) {
            System.out.println("Director approved the leave.");
        } else {
            if (nextApprover != null) {
                nextApprover.processRequest(request);
            } else {
                System.out.println("No one can approve this leave.");
            }
        }
    }

    @Override
    public void setSuccessor(Approver successor) {
        this.nextApprover = successor;
    }
}

// 客户端代码
public class ChainOfResponsibilityExample {
    public static void main(String[] args) {
        Approver manager = new Manager();
        Approver director = new Director();
        
        // 设置责任链
        manager.setSuccessor(director);

        LeaveRequest shortLeave = new LeaveRequest(3, "Family emergency");
        LeaveRequest longLeave = new LeaveRequest(15, "Extended vacation");

        manager.processRequest(shortLeave); // 输出:Manager approved the leave.
        manager.processRequest(longLeave); // 输出:Director approved the leave.
    }
}

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值