使用界面或抽象的设计模式[关闭]

问题描述 投票:1回答:1

我试图根据不同的纸张尺寸,单面或双面计算打印成本。所以这里是细节:

另外还需要支持其他纸张尺寸。

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

有人可以审查我的代码,并帮助我是否必须使用接口而不是抽象类?

这是我的代码:

PageBase:

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;
        }
    }
}  

PageFactory:

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);
    }
}
java oop design-patterns
1个回答
1
投票

对于你的问题,装饰师比工厂更优雅。

对于Decorator,您将需要一些类和接口:

  • 接口:彩色,边和页面。所有接口都有一个方法cost()来实现。
  • 课程:单面,双面,ColorPage,Blank WhitePage,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();
    }
}

这一行中的某些内容可以为您提供有关最佳对象组织的一些见解。

© www.soinside.com 2019 - 2024. All rights reserved.