【问题标题】:How to refactor these classes to interact each other?如何重构这些类以相互交互?
【发布时间】:2017-08-14 13:19:48
【问题描述】:

我的要求是使用 shape 的名称并使用 dimensions 绘制该形状,就像在方法 Draw('rectangle', 'l:10,w:20'); 中一样。

  1. 应根据形状类型验证尺寸。
  2. 可以重构这些类以添加更多类或更改层次结构。
  3. 不应使用像 reflection 这样的运行时检查。这个问题只需要通过类设计来解决。
  4. 不要在客户端方法Draw中使用if-elseswitch语句。

要求:

public static void main()
{
    // Provide the shape and it's dimensions
    Draw('rectangle', 'l:10,w:20');
    Draw('circle', 'r:15');
}

我创建了以下类。我通过创建两个类层次结构来考虑低(松散)耦合和高内聚,这样它们就可以自行增长。我负责绘制一个类并生成另一个类的维度。

我的问题是关于创建这些对象并相互交互以实现我的要求。

public abstract class Shape()
{
    Dimension dimension;
    public void abstract SetDimentions(Dimension dimension);
    public void abstract Draw()
}

public void Rectangle()
{
    void override SetDimensions(RectangleDimension dimension)
    {
    }

    void override Draw()
    {
        // Use the 'dimention' to draw
    }
}

public void Circle()
{
    void override SetDimensions(CircleDimension dimension)
    {
    }

    void override Draw()
    {
        // Use the 'dimention' to draw
    }
}

public class RectangleDimension
{
    public int length {get; set; }
    public int width { get; set; }
}

public class CircleDimension
{
    public int circle { get; set; }
}

【问题讨论】:

    标签: oop loose-coupling cohesion


    【解决方案1】:

    您需要在所使用的任何 OOP 技术中使用反射。你会收到一个 String"circle" 一样,你需要调用一个具有该名称的方法。

    这就是你可以在Java 中执行此操作的方法,也是您可以在C# 中执行此操作的方法。

    【讨论】:

    • 我不能使用反射。可以修改类层次结构或添加新类。
    • @wonderfulworld 然后您可以使用 if-else 条件检查字符串值,并在每种情况下调用相应的方法。
    • 你能用代码解释一下吗?我试图避免 if-elseswitch 声明。
    • @wonderfulworld 使用反射的目的是避免 if-else。如果没有反射,您将需要类似 if (shapeName.equals("circle")) {Draw("circle", params)}; else {/*...*/} 并且你有 shapeName 和 params 作为 Draw 的参数。
    猜你喜欢
    • 2013-09-04
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多