Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将一个类转换为另一个类的设计模式_Java - Fatal编程技术网

Java 将一个类转换为另一个类的设计模式

Java 将一个类转换为另一个类的设计模式,java,Java,我有一个叫做GoogleWeather的类,我想把它转换成另一个类CustomWeather 是否有任何设计模式可以帮助您转换类?在这种情况下,我将使用带有一系列静态方法的Mapper类: public final class Mapper { public static GoogleWeather from(CustomWeather customWeather) { GoogleWeather weather = new GoogleWeather(); //

我有一个叫做GoogleWeather的类,我想把它转换成另一个类CustomWeather


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

在这种情况下,我将使用带有一系列静态方法的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());

需要做出一个关键决定:

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

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

另一方面,如果需要转换的对象反映对源对象的更改,则可能需要以下内容:


此外,您还可以使用java.util.Function中的新Java8特性“Function”


中提供了更详细的说明。请看一看

您的层次结构是什么(CustomWeather是否扩展了GoogleWeather)?你说的“转换”是什么意思?如何转换?创建子类、重命名子类等?目前还不清楚您希望在“CustomWeather”类中得到什么Google Weather和CustomWeather之间没有继承关系这是使用Mapper的好方法吗?当然,这是有史以来最好的方法!(只是开玩笑,但是,嘿,我不推荐不好的解决方案)需要注意的是:这是一次性转换;源对象中的未来更改不会影响结果对象的字段。为什么要在此处执行类final?(我听说它使类)+1用于保持类型不依赖性,-1用于通过静态方法实现它,使使用这种不可测试的独立单元(没有一些疯狂的魔力)我不明白adapter和mapper appproche之间的区别在这种情况下使用适配器模式有什么好处?@user1549004:适配器是一个包装器-所有方法都被转发到源对象。这意味着对源对象的任何更新都将通过适配器传播。另一方面使用映射器类是一次性的-对源的任何更新通常不会影响转换的结果。如果对源的任何更新都不会影响转换的结果,请给我一个使用映射器类的示例。对不起,我的意思是影响结果*这不是关于转换的问题吗?这是只是一个简单的单向转换器-有效,但您可以在任何Java版本中以完全相同的方式实现它。
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;
    }
    ...
}