Change Unidirectional Association to Bidirectional(将单向关联改为双向关联)
生活随笔
收集整理的這篇文章主要介紹了
Change Unidirectional Association to Bidirectional(将单向关联改为双向关联)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
兩個類都需要使用對方特性,但其間只有一個單向連接
?重構:添加一個反向指針,并使修改函數能夠同時更新兩條連接
由哪個類負責控制關聯關系。建議單個類來操控,因為這樣就可以將所有處理關聯關系的邏輯安置于一地。
?? ?1、如果兩者都是引用對象,而期間的關聯是“一對多”關系,那么就由“擁有單一引用”的那一方承擔“控制者”角色。
?? ?2、如果某個對象是組成另一個對象的部件,那么由后者(整體)負責控制關聯關系。
?? ?3、如果兩者都是引用對象,而期間的關聯是“多對多”關系,那么隨便哪個對象控制關聯關系都可。
多對多場景:
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(将单向关联改为双向关联)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎么改HTML表单数据,form设置的数
- 下一篇: android applybatch,a