且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-07 14:44:36

有一个关键决定要做:

你们需要转换生成的对象来反映未来对源对象的更改吗?

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

If you do not need such functionality, then the simplest approach is to use a utility class with static methods that create a new object based on the fields of the source object, as mentioned in other answers.

另一方面,如果你需要转换的对象来反映对源对象的更改,您可能需要适配器设计的内容。模式

On the other hand, if you need the converted object to reflect changes to the source object, you would probably need something along the lines of the 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;
    }
    ...
}