简体   繁体   中英

Can one class implement both subject and observer sections of the observer design pattern?

I'm designing an enemy framework for java and working with observer. I'm wondering if it is possible | worth the effort to have one class implement both observer and subject in java?

I want to have an enemy interface which implements both subject and observer so that the enemies within a certain distance of each other can alert each other if a player or enemy is sighted.

Is there a better pattern to use here?

I think one of these would be slightly more appropriate to use than observer pattern, depending on actually how you want to implement your framework:

The trouble with subject / observer is that they involve registering / deregistering when your enemies move in / out of range of each other.

I would recommend implicit invocation or event-driven as follows:

  • Each time an enemy sights a player, generate an "event" that gets broadcast to all other enemies.
  • This event will have a coordinate to specify from where it was broadcasted.
  • For each enemy that receives the event (which is all of them), look at the coordinate and see if it's within a certain range of itself
    • If not, ignore it (and pretend as if it never heard it)
    • If so, do something as required.

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