【问题标题】:Design pattern to convert a class to another [closed]将一个类转换为另一个类的设计模式[关闭]
【发布时间】:2012-08-06 16:15:32
【问题描述】:

我有一个名为 GoogleWeather 的类,我想将它转换为另一个类 CustomWeather。

是否有任何设计模式可以帮助您转换类?

【问题讨论】:

  • 您的层次结构是什么(CustomWeather 是否扩展了 GoogleWeather)? “转换”是什么意思?
  • 如何转换为?创建一个子类,重命名它,等等?目前尚不清楚您在“CustomWeather”类中想要什么
  • GoogleWeather 和 CustomWeather 之间没有继承

标签: java


【解决方案1】:

在这种情况下,我会使用带有一堆静态方法的 Mapper 类:

public final class Mapper {

   public static GoogleWeather from(CustomWeather customWeather) {
      GoogleWeather weather = new GoogleWeather();
      // set the properties based on customWeather
      return weather;
   }

   public static CustomWeather from(GoogleWeather googleWeather) {
      CustomWeather weather = new CustomWeather();
      // set the properties based on googleWeather
      return weather;
   }
}

所以类之间没有依赖关系。

示例用法:

CustomWeather weather = Mapper.from(getGoogleWeather());

【讨论】:

  • 使用 Mapper 是否是一种好方法?
  • 当然,这是有史以来最好的方法! (开个玩笑,但是嘿,我不会在这里推荐糟糕的解决方案)
  • 需要注意的一点:这是一次性转换;源对象的未来更改不会影响结果对象的字段。
  • +1 用于保持类型不依赖,-1 用于通过静态方法实现它,使使用此不可测试的单元独立(没有一些疯狂的魔法)
  • @alex 对,测试这个实用程序类的静态方法很容易,但是使用这种方法测试类会很困难,因为你不能轻易地模拟它们。通过不使用静态方法而是使其成为实例的普通 api,您可以使用依赖注入并模拟 Mapper 逻辑。
【解决方案2】:

需要做出一个关键决定:

您是否需要转换生成的对象来反映对源对象的未来更改?

如果您不需要此类功能,那么最简单的方法是使用具有静态方法的实用程序类,该方法根据源对象的字段创建新对象,如其他答案中所述。

另一方面,如果您需要转换后的对象来反映对源对象的更改,您可能需要类似于Adapter design pattern 的内容:

public class GoogleWeather {
    ...
    public int getTemperatureCelcius() {
        ...
    }
    ...
}

public interface CustomWeather {
    ...
    public int getTemperatureKelvin();
    ...
}

public class GoogleWeatherAdapter implements CustomWeather {
    private GoogleWeather weather;
    ...
    public int getTemperatureKelvin() {
        return this.weather.getTemperatureCelcius() + 273;
    }
    ...
}

【讨论】:

  • 我不明白适配器和映射器应用程序之间的区别在这种情况下使用适配器模式有什么好处?
  • @user1549004:适配器是一个包装器 - 所有方法都转发到源对象。这意味着对源对象的任何更新都会通过适配器传播。另一方面,使用映射器类是一次性的 - 对源的任何更新通常不会影响转换结果。
  • 您能否给我一个使用映射器类的示例,以防对源的任何更新都不会影响转换结果。
  • 对不起,我的意思是影响结果*
  • 不是转换的问题吗?
【解决方案3】:

此外,您还可以使用 java.util.function 中的新 Java8 功能“Function”。

http://www.leveluplunch.com/java/tutorials/016-transform-object-class-into-another-type-java8/ 中提供了更详细的解释。请看一看!

【讨论】:

  • 这只是一个简单的单向转换器 - 有效,但您可以在任何 Java 版本中以完全相同的方式实现它。
猜你喜欢
  • 2023-03-14
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多