java - 使用接口(interface)或抽象的设计模式

标签 java oop design-patterns

我正在尝试根据不同的纸张尺寸(单面或双面)计算打印成本。这是详细信息:

还需要将来添加对其他纸张尺寸的支持。

根据我的设计,开发人员只需创建一个 A5 类即可支持其他纸张尺寸,并在工厂类中添加其他条件。

有人可以检查我的代码并帮助我确定是否必须使用接口(interface)而不是抽象类吗?

这是我的代码:

页面基数:

public abstract class PageBase {
    abstract double GetCost(int total, int color, boolean isSingleSide);
    abstract void CalculateUnitPrice(boolean isSingleSide);
}  

A4Page 类:

public class A4Page extends PageBase {
    public double blackAndWhitePrintUnitCost;
    public double colorPrintUniCost;

    @Override
    public double GetCost(int total, int color, boolean isSingleSide) {
        CalculateUnitPrice(isSingleSide);
        return color* colorPrintUniCost + (total-color)* blackAndWhitePrintUnitCost;
    }

    @Override
    public void CalculateUnitPrice(boolean isSingleSide) {
        if (isSingleSide) {
            this.blackAndWhitePrintUnitCost = 0.15;
            this.colorPrintUniCost = 0.25;
        }
        else {
            this.blackAndWhitePrintUnitCost = 0.10;
            this.colorPrintUniCost = 0.20;
        }
    }
}  

页面工厂:

public class PageFactory {

    public PageBase GetPage(String pageType) {
        switch (pageType.toUpperCase()) {
            case "A4":
                return new A4Page();
            default:
                return new A4Page();
        }
    }
}

主要:

public class Main {
    public static void Main() {
        //read
        PageFactory pageFactory = new PageFactory();
        PageBase page = pageFactory.GetPage("A4");
        page.GetCost(0,0,false);
    }
}

最佳答案

对于您的问题,装饰器比工厂更优雅。

对于装饰器,您将需要一些类和接口(interface):

  • 界面:彩色、侧面和页面。所有接口(interface)都有一个要实现的方法 cost()
  • 类:SingleSide、DoubleSide、ColorPage、BlankAndWhitePage、A4

用法:

Page page1 = new A4(new SingleSide(new ColorPage()))
Page page2 = new A4(new DoubleSide(new BlankAndWhitePage()))

page1.cost();

您需要为每个组件添加一些值,进行求和并给出预期值。每个对象都有一个“成本”。

一些内部结构:

class A4 implements Page {
    //constructor
    private Side side;

    public BigDecimal cost() {
        return this.valueA4 + side.cost();
    }
}

class SingleSide implements Side {
    //constructor
    private Colored colored;

    public BigDecimal cost() {
        return this.valueSingleSided+ colored.cost();
    }
}

这一行中的内容可以让您了解有关最佳对象组织的一些见解。

关于java - 使用接口(interface)或抽象的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49052646/

相关文章:

Java使用什么数据结构来处理具有更多不同数据类型的List?

java - 用于方法上 Java 注释的自定义内容辅助模板

Java 初学者 : convert an image to a binary array

oop - 可以应用 Liskov 替换原则(php 示例)吗?

python-3.x - 在 python 的 __format__ 方法中创建自定义格式说明符

Java面向对象编程: referencing subclass object

javascript - 类层次结构 : Is there a cleaner pattern for this?

java - 创建Factory来创建领域对象的正确方法

Java 抽象 : abstract class delegates abstractions vs. 具体类使用通用抽象

java - 如果 XAResource 是 Tx 中涉及的唯一资源,则应调用 XAResource.prepare()