![](/img/trans.png)
[英]Java - Update attributes of an object from a different class with protected methods
[英]Different methods need different attributes in one object
我有給定的Web服務。 (這只是一個例子,實際的例子比較復雜,但是存在相同的問題。)該服務具有三種方法,並且這三種方法都以一個人作為參數,並且還需要其他的東西。 (我無法更改實體或方法。)
實體(人)(它只有一個默認構造函數):
private String name;
private int age;
private Address address;
private List<String> hobbies;
private List<Person> friends;
我需要從我自己的對象中填充對象。 我需要寫一個“轉換器”。 最佳做法是什么?
我的解決方案:
我認為您可以通過適當使用裝飾器模式來獲得所需的東西: https : //en.wikipedia.org/wiki/Decorator_pattern
創建僅設置必填字段的構建器聽起來不錯。
您可以從每個類繼承此類,並實現自己的構造函數
public class Target { // fields } public class Purpose1 extends Target { public Purpose1(String name, int age) { // set fields or do whatever you wish } } public class Purpose2 extends Target { public Purpose2(String address, String name, int age) { // set fields or do whatever you wish } } public class Purpose3 extends Target { public Purpose3(...) { // set fields or do whatever you wish } }
然后,您可以使用需要Target
類的子類實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.