gpt4 book ai didi

design-patterns - 我们应该在哪里使用模板方法 - 模式?

转载 作者:行者123 更新时间:2023-12-04 04:54:29 24 4
gpt4 key购买 nike

谁能告诉我一些应该使用模板方法 - 模式的示例情况?

根据您自己的经验,给我一些实际使用。

(到目前为止,我发现它仅对 DA 层中的映射数据有用。对不起!!!)

最佳答案

我试图给你一些现实世界的例子,以及一些应该使用模板方法模式的常见情况。

  • 当您希望您的程序“开放以供扩展”和“关闭以供修改”时。 这意味着模块的行为可以扩展,这样我们可以使模块以新的和不同的方式运行作为需求应用程序的变化,或者满足新应用程序的需要。但是,这样的模块的源代码是不可侵犯的。任何人都不能对其源代码进行更改。在下面的例子中,您可以添加新的工资计算方式(如Remotely 类)而不改变之前的代码。
    public abstract class Salary {

    public final void calculate() {
    System.out.println("First shared tasks is done.");
    getBaseSalary();
    System.out.println("Second shared tasks is done.");
    }

    public abstract void getBaseSalary();

    }

    public class Hourly extends Salary {

    @Override
    public void getBaseSalary() {
    System.out.println("Special Task is done.");
    }

    }

    public class Test {

    public static void main(String[] args) {
    Salary salary = ....
    salary.calculate();
    }
    }
  • 当您面对许多通过延迟算法的某些步骤而重复的相同代码行时。 当您实现方法或函数的内容时,您会发现代码的某些部分因一种类型而异。该部分的特点是可以重新定义或修改方法或函数的这些部分,而无需更改算法(方法或函数)的主要结构。例如,如果您想在不使用此模式的情况下解决此问题,您将面临以下示例:

  • 功能0:功能1:...功能N:
    1       1               1
    2 2 2
    ... ... ...
    5 6 n
    3 3 3
    4 4 4
    ... ... ...

    如您所见,部分 cods 5、6、n 因一个功能而异,而另一个功能则不同,但是您共享的部分(例如 1、2、3、4)是重复的。让我们考虑一个使用著名的 java 库的解决方案。
    public abstract class InputStream implements Closeable {

    public abstract int read() throws IOException;

    public int read(byte b[], int off, int len) throws IOException {
    ....

    int c = read();
    ....
    }

    ....

    }

    public class ByteArrayInputStream extends InputStream {

    ...

    public synchronized int read() {
    return (pos < count) ? (buf[pos++] & 0xff) : -1;
    }
    ...
    }
  • 当您作为框架的设计者时,希望您的客户只使用作为参数传递给您的框架的任何可执行代码,预期在给定时间回调(执行)该参数。 此执行可能像在同步回调中​​那样立即执行,也可能像在异步回调中那样在稍后发生。让我们考虑一个著名的。
    public abstract class HttpServlet extends GenericServlet 
    implements java.io.Serializable {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    ...
    }

    protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    ....
    doGet(req, resp);
    ...
    }
    ...
    }
    }

    public class MyServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    //do something
    ...
    }
    ...
    }
  • 关于design-patterns - 我们应该在哪里使用模板方法 - 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1553856/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com