oop - How to do logic based on object ID -


suppose have game, there buildings sorted type. each type represented separate class, have uncommon logic buildings of same type. how 1 implement kind of behaviour?

for example, can identify buildings id, can have giant switch or command pattern inside building type class. think not right approach.

another approach have different class divergent logic. proposes lot of small classes.

this polymorphism aims solve, , 1 of big differences between procedural , oop programming. can achieve through extending base class, or implementing interface. here extending base class:

public abstract class building {     abstract void destroy(); }  public brickbuilding extends building {     @override     public void destroy() {         bricks.falltoground();     } }  public haybuilding extends building {     @override     public void destroy() {         straw.blowinwind();     } } 

in places in code have used switch statement switch on building type, hold reference abstract building type, , call method destroy() on it:

public class buildingdestroyer {     public void rampage() {         for(building building : allthebuildings) {             // brickbuilding, or haybuilding             building.destroy();         }     } } 

or, address concern having lot of small types, can 'inject' destroy behaviour want common building type, so...albeing, end lot of different destroy behaviour classes too...so, might not solution.

public interface destroybehaviour {     void destroy(building building); }  public class building {     private int id;     public destroybehaviour destroybehaviour;      public building(int id, destroybehaviour destroybehaviour) {         this.id = id;         this.destroybehaviour = destroybehaviour;     }      public void destroy() {         destroybehaviour.destroy(this); // or along lines;     } } 

Comments

Popular posts from this blog

tcpdump - How to check if server received packet (acknowledged) -