设计模式之模板模式(Template Model)

本文介绍策略模式的应用场景及其实现方式,通过一个打印服务的例子展示了如何让用户在多种算法或策略间进行选择。策略模式允许算法独立于使用它的客户端,使得算法可以自由切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.使用场景.有个算法有许多版本,使用时用户决定使用哪一个版本。(比如排序算法,有插入排序,选择排序,冒泡排序,快速排序,归并排序等许多排序算法,在使用的时候,用户决定使用哪一个具体的排序算法)。
        
  2.实现
        1)定义一个抽象类

        2)每一个继承的子类实现一个版本。


PS:模板方法模式和策略模式的区别:

    前者定义一个抽象类,后者定义一个接口(interface),两者分别把共同的部分放到抽象类和接口中。


Example Code:

抽象类PrintIAbstract提供打印服务,具体的打印服务由子类PrintA和PrintB来实现,PrintContext是上下文类,用户可以通过该类调用打印服务,代码清单如下:


public class PrintContext {
    private PrintIAbstract printInterface;
    
    public PrintContext(PrintIAbstract pi){
        this.printInterface = pi;
    }
    
    public void run(){
        this.printInterface.print();
    }
    
    public void changeStrategy(PrintIAbstract pi){
        printInterface = pi;
    }

}


public abstract class PrintIAbstract {
    abstract public void print();
}

public class PrintA extends PrintIAbstract{
    public void print() {
        System.out.println("this is printA");
    }
}

public class PrintB extends PrintIAbstract{

    public void print() {
        System.out.println("this is printB");
    }

}

public class maintest {

    public static void main(String[] args) {
        PrintContext pcContext = new PrintContext(new PrintA());
        pcContext.run();
        
        pcContext.changeStrategy(new PrintB());
        pcContext.run();
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值