日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Change Unidirectional Association to Bidirectional(将单向关联改为双向关联)

發布時間:2024/7/23 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Change Unidirectional Association to Bidirectional(将单向关联改为双向关联) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

兩個類都需要使用對方特性,但其間只有一個單向連接

?重構:添加一個反向指針,并使修改函數能夠同時更新兩條連接

由哪個類負責控制關聯關系。建議單個類來操控,因為這樣就可以將所有處理關聯關系的邏輯安置于一地。

?? ?1、如果兩者都是引用對象,而期間的關聯是“一對多”關系,那么就由“擁有單一引用”的那一方承擔“控制者”角色。
?? ?2、如果某個對象是組成另一個對象的部件,那么由后者(整體)負責控制關聯關系。
?? ?3、如果兩者都是引用對象,而期間的關聯是“多對多”關系,那么隨便哪個對象控制關聯關系都可。

public class Order {private Customer customer;public Customer getCustomer() {return customer;}// 建議:一對多關系里,【一方】維護關系.public void setCustomer(Customer arg) {if (this.customer != null) {this.customer.friendOrders().remove(this);}this.customer = arg;if (this.customer != null) {this.customer.friendOrders().add(this);}} }public class Customer {private Set<Order> orders = new HashSet<>();public Set<Order> friendOrders() {/*should only be used by Order when modifying the association*/return orders;}// 【多方】也修改連接,直接調用【一方】的函數.public void addOrder(Order arg) {arg.setCustomer(this);} }

多對多場景:

public class Order {private Set<Customer> customers;// controlling methods.public void addCustomer(Customer arg) {arg.friendOrders().add(this);this.customers.add(arg);}public void removeCustomer(Customer arg) {arg.friendOrders().remove(this);this.customers.remove(arg);} }public class Customer {private Set<Order> orders = new HashSet<>();public Set<Order> friendOrders() {/*should only be used by Order when modifying the association*/return orders;}// 使用控制方函數.public void addOrder(Order arg) {arg.addCustomer(this);}public void removOrder(Order arg) {arg.removeCustomer(this);} }

總結

以上是生活随笔為你收集整理的Change Unidirectional Association to Bidirectional(将单向关联改为双向关联)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。