简体   繁体   中英

Referring generically to objects in different families in Java

I have classes belonging to the family Foo ( BabyFoo , MamaFoo , PapaFoo ) as well as classes belonging to the family Bar ( BabyBar , MamaBar , PapaBar ). Within each family, it is easy to refer to the members of the family. For instance, when MamaFoo refers to her own child, she refers explicitly to BabyFoo . But there are instances when class Lou runs code on the members of a family ( Baby , Mama , Papa ) without knowing which family is handling the request.

How can Lou refer generically in Java to a member of either family?

My (poor) solution so far is to use delegation. Lou does not run code on members of the two families. Instead two gateway classes FamilyFoo and FamilyBar handle all incoming requests from Lou .

FamilyFoo and FamilyBar in turn refer explicitly to classes in their family. This solution turned out to be poor because it results in considerable code duplication, even though polymorphism ( Lou delegates to a Family reference , a parent of both FamilyFoo and FamilyBar ) means that some code economy is achieved.

Can you do better?

You should use either an interface which Bar and Foo can implement if it's going to be the same operations for all subtypes.

Instead, if it makes sense you can make a super class which both Bar and Foo can extend. From your explanation I can't be sure which is better. I'd need more information.

EDIT : You can use generic family members such as Baby<T> , Mama<T> , Papa<T> for which T represents the family.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM