Change Unidirectional Association to Bidirectional(将单向关联改为双向关联)
生活随笔
收集整理的這篇文章主要介紹了
Change Unidirectional Association to Bidirectional(将单向关联改为双向关联)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
兩個(gè)類都需要使用對(duì)方特性,但其間只有一個(gè)單向連接
?重構(gòu):添加一個(gè)反向指針,并使修改函數(shù)能夠同時(shí)更新兩條連接
由哪個(gè)類負(fù)責(zé)控制關(guān)聯(lián)關(guān)系。建議單個(gè)類來(lái)操控,因?yàn)檫@樣就可以將所有處理關(guān)聯(lián)關(guān)系的邏輯安置于一地。
?? ?1、如果兩者都是引用對(duì)象,而期間的關(guān)聯(lián)是“一對(duì)多”關(guān)系,那么就由“擁有單一引用”的那一方承擔(dān)“控制者”角色。
?? ?2、如果某個(gè)對(duì)象是組成另一個(gè)對(duì)象的部件,那么由后者(整體)負(fù)責(zé)控制關(guān)聯(lián)關(guān)系。
?? ?3、如果兩者都是引用對(duì)象,而期間的關(guān)聯(lián)是“多對(duì)多”關(guān)系,那么隨便哪個(gè)對(duì)象控制關(guān)聯(lián)關(guān)系都可。
多對(duì)多場(chǎng)景:
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;}// 使用控制方函數(shù).public void addOrder(Order arg) {arg.addCustomer(this);}public void removOrder(Order arg) {arg.removeCustomer(this);} }總結(jié)
以上是生活随笔為你收集整理的Change Unidirectional Association to Bidirectional(将单向关联改为双向关联)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 怎么改HTML表单数据,form设置的数
- 下一篇: android applybatch,a