简体   繁体   English

如何实现策略设计模式

[英]How to implement strategy design pattern

Can anyone tell how can we implement Strategy design pattern in the following code.谁能告诉我们如何在下面的代码中实现策略设计模式。 I have gone through various links but not fully clear about implementing it.我已经浏览了各种链接,但对实施它并不完全清楚。 Question is: Calculate points and display the report in PDF or HTML using Strategy Design Pattern.问题是:使用策略设计模式计算点数并在 PDF 或 HTML 中显示报告。 Below is the code already available.下面是已经可用的代码。 Customer, Movie and Rental are classes already created: Customer、Movie 和 Rental 是已经创建的类:

  1. Customer.java客户.java

     public class Customer { private String _name; private Vector _rentals = new Vector(); public Customer(String name) { _name = name; }; public void addRental(Rental arg) { _rentals.addElement(arg); } public String getName() { return _name; } public static void main(String[] args) { Customer c = new Customer("ABC"); Movie m = new Movie("Title", 1); Rental r = new Rental(m, 10); c.addRental(r); // Rental calculation String s = c.statement(); System.out.println("s: " + s); } public String statement() { double totalAmount = 0; int frequentRenterPoints = 0; Enumeration rentals = _rentals.elements(); String result = "Rental Record for " + getName() + "\n"; while (rentals.hasMoreElements()) { double thisAmount = 0; Rental each = (Rental) rentals.nextElement(); // determine amounts for each line switch (each.getMovie().getPriceCode()) { case Movie.REGULAR: thisAmount += 2; if (each.getDaysRented() > 2) thisAmount += (each.getDaysRented() - 2) * 1.5; break; case Movie.NEW_RELEASE: thisAmount += each.getDaysRented() * 3; break; case Movie.CHILDRENS: thisAmount += 1.5; if (each.getDaysRented() > 3) thisAmount += (each.getDaysRented() - 3) * 1.5; break; } // add frequent // renter points frequentRenterPoints++; // add bonus for a two day new release rental if ((each.getMovie().getPriceCode() == Movie.NEW_RELEASE) && each.getDaysRented() > 1) frequentRenterPoints++; // show figures for this rental result += "\t" + each.getMovie().getTitle() + "\t" + String.valueOf(thisAmount) + "\n"; totalAmount += thisAmount; } // add footer lines result += "Amount owed is " + String.valueOf(totalAmount) + "\n"; result += "You earned " + String.valueOf(frequentRenterPoints) + " frequent renter points"; return result; } }
  2. Movie.java电影.java

     public class Movie { public static final int CHILDRENS = 2; public static final int REGULAR = 0; public static final int NEW_RELEASE = 1; private String _title; private int _priceCode; public Movie(String title, int priceCode) { _title = title; _priceCode = priceCode; } public int getPriceCode() { return _priceCode; } public void setPriceCode(int arg) { _priceCode = arg; } public String getTitle() { return _title; }; }
  3. Rental.java出租.java

     public class Rental { private Movie _movie; private int _daysRented; public Rental(Movie movie, int daysRented) { _movie = movie; _daysRented = daysRented; } public int getDaysRented() { return _daysRented; } public Movie getMovie() { return _movie; } }

Your task is "display the report in PDF or HTML using Strategy Design Pattern", so strategy will be applied here.您的任务是“使用策略设计模式在 PDF 或 HTML 中显示报告”,因此此处将应用策略。 Before display Report you should have all computed data (keep the work as was done) and after just pass data and choose appropriate report type.在显示报告之前,您应该拥有所有计算数据(保持工作已完成),然后只需传递数据并选择适当的报告类型。

public interface IReport 
{
    public void printReport(String data);
}

public class ReportHTML implements IReport
{
    @Override
    public void printReport(String data) {
        System.out.println("Html Report with data="+data);  
    }
}

public class ReportPDF implements IReport{
    @Override
    public void printReport(String data) {
        System.out.println("PDF Report with data="+data);   
    }
}

public class Test {
    public static void main(String[] args)
    {
        //do whatever computation concerning business logic
        //after for print pass computed data and chose report type as needed
        IReport ir = new ReportHTML();
        ir.printReport("[Customers, Movie, Rental]");
        ir = new ReportPDF();
        ir.printReport("[Customers, Movie, Rental]");
    }
}

Output: Output:

Html Report with data=[Customers, Movie, Rental]
PDF Report with data=[Customers, Movie, Rental]

HTML and PDF are display formats. HTML 和 PDF 是显示格式。 A strategy is just a pluggable algorithm, usually defined by an interface.策略只是一种可插入的算法,通常由接口定义。 Since the task is to display the report and the pluggable part is how to display it (the algorithm), you need a display strategy.由于任务是显示报表,而可插拔部分是如何显示它(算法),因此您需要一个显示策略。 As for names, many people would call the interface ReportDisplayStrategy and that's fine, but often I think the design pattern name is just pollution, so I'd consider something more like ReportRenderer.至于名称,很多人会调用接口 ReportDisplayStrategy 这很好,但我经常认为设计模式名称只是污染,所以我会考虑更像 ReportRenderer 的东西。 If the output is always a file (there's a lot more you could do here), the interface might look like:如果 output 始终是一个文件(您可以在此处执行更多操作),则界面可能如下所示:

interface ReportRenderer
{ 
    File render(Report report)
}

The rest is matter of making your report object and writing the renderer implementations for PDF and HTML. rest 是制作报告 object 并为 PDF 和 Z4C4AD5FCED0037A3F7A44DB1 编写渲染器实现的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM